BattleWindow.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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 - 67, pos.y));
  165. unitActionWindow = std::make_shared<UnitActionPanel>(owner);
  166. unitActionWindow->moveTo(Point(pos.x + pos.w + 15, 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. setPositionInfoWindow();
  186. createTimerInfoWindows();
  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 = ENGINE->screenDimensions().x >= 1050 && hero != nullptr && hero->hasSpellbook();
  195. bool unitActionWindowVisible = ENGINE->screenDimensions().x >= 1050;
  196. quickSpellWindow->setEnabled(quickSpellWindowVisible);
  197. unitActionWindow->setEnabled(unitActionWindowVisible);
  198. setPositionInfoWindow();
  199. createTimerInfoWindows();
  200. ENGINE->windows().totalRedraw();
  201. }
  202. void BattleWindow::createTimerInfoWindows()
  203. {
  204. OBJECT_CONSTRUCTION;
  205. int xOffsetAttacker = quickSpellWindow->isDisabled() ? 0 : -53;
  206. int xOffsetDefender = unitActionWindow->isDisabled() ? 0 : 53;
  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 (ENGINE->screenDimensions().x >= 1000)
  214. attackerTimerWidget = std::make_shared<TurnTimerWidget>(Point(-92 + xOffsetAttacker, 1), attacker);
  215. else
  216. attackerTimerWidget = std::make_shared<TurnTimerWidget>(Point(1, 135), attacker);
  217. }
  218. if (defender.isValidPlayer())
  219. {
  220. if (ENGINE->screenDimensions().x >= 1000)
  221. defenderTimerWidget = std::make_shared<TurnTimerWidget>(Point(pos.w + 16 + xOffsetDefender, 1), 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 : -53;
  317. int xOffsetDefender = unitActionWindow->isDisabled() ? 0 : 53;
  318. if(defenderHeroWindow)
  319. {
  320. Point position = (ENGINE->screenDimensions().x >= 1000)
  321. ? Point(pos.x + pos.w + 15 + xOffsetDefender, pos.y + 60)
  322. : Point(pos.x + pos.w -79, pos.y + 195);
  323. defenderHeroWindow->moveTo(position);
  324. }
  325. if(attackerHeroWindow)
  326. {
  327. Point position = (ENGINE->screenDimensions().x >= 1000)
  328. ? Point(pos.x - 93 + xOffsetAttacker, pos.y + 60)
  329. : Point(pos.x + 1, pos.y + 195);
  330. attackerHeroWindow->moveTo(position);
  331. }
  332. if(defenderStackWindow)
  333. {
  334. Point position = (ENGINE->screenDimensions().x >= 1000)
  335. ? Point(pos.x + pos.w + 15 + xOffsetDefender, defenderHeroWindow ? defenderHeroWindow->pos.y + 210 : pos.y + 60)
  336. : Point(pos.x + pos.w -79, defenderHeroWindow ? defenderHeroWindow->pos.y : pos.y + 195);
  337. defenderStackWindow->moveTo(position);
  338. }
  339. if(attackerStackWindow)
  340. {
  341. Point position = (ENGINE->screenDimensions().x >= 1000)
  342. ? Point(pos.x - 93 + xOffsetAttacker, attackerHeroWindow ? attackerHeroWindow->pos.y + 210 : pos.y + 60)
  343. : Point(pos.x + 1, attackerHeroWindow ? attackerHeroWindow->pos.y : pos.y + 195);
  344. attackerStackWindow->moveTo(position);
  345. }
  346. }
  347. void BattleWindow::updateHeroInfoWindow(uint8_t side, const InfoAboutHero & hero)
  348. {
  349. std::shared_ptr<HeroInfoBasicPanel> panelToUpdate = side == 0 ? attackerHeroWindow : defenderHeroWindow;
  350. panelToUpdate->update(hero);
  351. }
  352. void BattleWindow::updateStackInfoWindow(const CStack * stack)
  353. {
  354. OBJECT_CONSTRUCTION;
  355. bool showInfoWindows = settings["battle"]["stickyHeroInfoWindows"].Bool();
  356. if(stack && stack->unitSide() == BattleSide::DEFENDER)
  357. {
  358. defenderStackWindow = std::make_shared<StackInfoBasicPanel>(stack, true);
  359. defenderStackWindow->setEnabled(showInfoWindows);
  360. }
  361. else
  362. defenderStackWindow = nullptr;
  363. if(stack && stack->unitSide() == BattleSide::ATTACKER)
  364. {
  365. attackerStackWindow = std::make_shared<StackInfoBasicPanel>(stack, true);
  366. attackerStackWindow->setEnabled(showInfoWindows);
  367. }
  368. else
  369. attackerStackWindow = nullptr;
  370. setPositionInfoWindow();
  371. createTimerInfoWindows();
  372. }
  373. void BattleWindow::heroManaPointsChanged(const CGHeroInstance * hero)
  374. {
  375. if(hero == owner.attackingHeroInstance || hero == owner.defendingHeroInstance)
  376. {
  377. InfoAboutHero heroInfo = InfoAboutHero();
  378. heroInfo.initFromHero(hero, InfoAboutHero::INBATTLE);
  379. updateHeroInfoWindow(hero == owner.attackingHeroInstance ? 0 : 1, heroInfo);
  380. }
  381. else
  382. {
  383. logGlobal->error("BattleWindow::heroManaPointsChanged: 'Mana points changed' called for hero not belonging to current battle window");
  384. }
  385. }
  386. void BattleWindow::activate()
  387. {
  388. ENGINE->setStatusbar(console);
  389. CIntObject::activate();
  390. GAME->interface()->cingconsole->activate();
  391. }
  392. void BattleWindow::deactivate()
  393. {
  394. ENGINE->setStatusbar(nullptr);
  395. CIntObject::deactivate();
  396. GAME->interface()->cingconsole->deactivate();
  397. }
  398. bool BattleWindow::captureThisKey(EShortcut key)
  399. {
  400. return owner.openingPlaying();
  401. }
  402. void BattleWindow::keyPressed(EShortcut key)
  403. {
  404. if (owner.openingPlaying())
  405. {
  406. owner.openingEnd();
  407. return;
  408. }
  409. InterfaceObjectConfigurable::keyPressed(key);
  410. }
  411. void BattleWindow::clickPressed(const Point & cursorPosition)
  412. {
  413. if (owner.openingPlaying())
  414. {
  415. owner.openingEnd();
  416. return;
  417. }
  418. InterfaceObjectConfigurable::clickPressed(cursorPosition);
  419. }
  420. void BattleWindow::tacticPhaseStarted()
  421. {
  422. auto menuBattle = widget<CIntObject>("menuBattle");
  423. auto console = widget<CIntObject>("console");
  424. auto menuTactics = widget<CIntObject>("menuTactics");
  425. auto tacticNext = widget<CIntObject>("tacticNext");
  426. auto tacticEnd = widget<CIntObject>("tacticEnd");
  427. menuBattle->disable();
  428. console->disable();
  429. menuTactics->enable();
  430. tacticNext->enable();
  431. tacticEnd->enable();
  432. redraw();
  433. }
  434. void BattleWindow::tacticPhaseEnded()
  435. {
  436. auto menuBattle = widget<CIntObject>("menuBattle");
  437. auto console = widget<CIntObject>("console");
  438. auto menuTactics = widget<CIntObject>("menuTactics");
  439. auto tacticNext = widget<CIntObject>("tacticNext");
  440. auto tacticEnd = widget<CIntObject>("tacticEnd");
  441. menuBattle->enable();
  442. console->enable();
  443. menuTactics->disable();
  444. tacticNext->disable();
  445. tacticEnd->disable();
  446. redraw();
  447. }
  448. void BattleWindow::bOptionsf()
  449. {
  450. if (owner.actionsController->heroSpellcastingModeActive())
  451. return;
  452. ENGINE->cursor().set(Cursor::Map::POINTER);
  453. ENGINE->windows().createAndPushWindow<SettingsMainWindow>(&owner);
  454. }
  455. void BattleWindow::bSurrenderf()
  456. {
  457. if (owner.actionsController->heroSpellcastingModeActive())
  458. return;
  459. int cost = owner.getBattle()->battleGetSurrenderCost();
  460. if(cost >= 0)
  461. {
  462. std::string enemyHeroName = owner.getBattle()->battleGetEnemyHero().name;
  463. if(enemyHeroName.empty())
  464. {
  465. logGlobal->warn("Surrender performed without enemy hero, should not happen!");
  466. enemyHeroName = "#ENEMY#";
  467. }
  468. 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."
  469. owner.curInt->showYesNoDialog(surrenderMessage, [this](){ reallySurrender(); }, nullptr);
  470. }
  471. }
  472. void BattleWindow::bFleef()
  473. {
  474. if (owner.actionsController->heroSpellcastingModeActive())
  475. return;
  476. if ( owner.getBattle()->battleCanFlee() )
  477. {
  478. auto ony = std::bind(&BattleWindow::reallyFlee,this);
  479. owner.curInt->showYesNoDialog(LIBRARY->generaltexth->allTexts[28], ony, nullptr); //Are you sure you want to retreat?
  480. }
  481. else
  482. {
  483. std::vector<std::shared_ptr<CComponent>> comps;
  484. std::string heroName;
  485. //calculating fleeing hero's name
  486. if (owner.attackingHeroInstance)
  487. if (owner.attackingHeroInstance->tempOwner == owner.curInt->cb->getPlayerID())
  488. heroName = owner.attackingHeroInstance->getNameTranslated();
  489. if (owner.defendingHeroInstance)
  490. if (owner.defendingHeroInstance->tempOwner == owner.curInt->cb->getPlayerID())
  491. heroName = owner.defendingHeroInstance->getNameTranslated();
  492. //calculating text
  493. auto txt = boost::format(LIBRARY->generaltexth->allTexts[340]) % heroName; //The Shackles of War are present. %s can not retreat!
  494. //printing message
  495. owner.curInt->showInfoDialog(boost::str(txt), comps);
  496. }
  497. }
  498. void BattleWindow::reallyFlee()
  499. {
  500. owner.giveCommand(EActionType::RETREAT);
  501. ENGINE->cursor().set(Cursor::Map::POINTER);
  502. }
  503. void BattleWindow::reallySurrender()
  504. {
  505. if (owner.curInt->cb->getResourceAmount(EGameResID::GOLD) < owner.getBattle()->battleGetSurrenderCost())
  506. {
  507. owner.curInt->showInfoDialog(LIBRARY->generaltexth->allTexts[29]); //You don't have enough gold!
  508. }
  509. else
  510. {
  511. owner.giveCommand(EActionType::SURRENDER);
  512. ENGINE->cursor().set(Cursor::Map::POINTER);
  513. }
  514. }
  515. void BattleWindow::setPossibleActions(const std::vector<PossiblePlayerBattleAction> & actions)
  516. {
  517. unitActionWindow->setPossibleActions(actions);
  518. }
  519. void BattleWindow::bAutofightf()
  520. {
  521. if (owner.actionsController->heroSpellcastingModeActive())
  522. return;
  523. if(settings["battle"]["endWithAutocombat"].Bool() && onlyOnePlayerHuman)
  524. {
  525. endWithAutocombat();
  526. return;
  527. }
  528. //Stop auto-fight mode
  529. if(owner.curInt->isAutoFightOn)
  530. {
  531. assert(owner.curInt->autofightingAI);
  532. owner.curInt->isAutoFightOn = false;
  533. logGlobal->trace("Stopping the autofight...");
  534. }
  535. else if(!owner.curInt->autofightingAI)
  536. {
  537. owner.curInt->isAutoFightOn = true;
  538. blockUI(true);
  539. auto ai = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  540. AutocombatPreferences autocombatPreferences = AutocombatPreferences();
  541. autocombatPreferences.enableSpellsUsage = settings["battle"]["enableAutocombatSpells"].Bool();
  542. ai->initBattleInterface(owner.curInt->env, owner.curInt->cb, autocombatPreferences);
  543. ai->battleStart(owner.getBattleID(), owner.army1, owner.army2, int3(0,0,0), owner.attackingHeroInstance, owner.defendingHeroInstance, owner.getBattle()->battleGetMySide(), false);
  544. owner.curInt->registerBattleInterface(ai);
  545. owner.requestAutofightingAIToTakeAction();
  546. }
  547. }
  548. void BattleWindow::bSpellf()
  549. {
  550. if (owner.actionsController->heroSpellcastingModeActive())
  551. return;
  552. if (!owner.makingTurn())
  553. return;
  554. auto myHero = owner.currentHero();
  555. if(!myHero)
  556. return;
  557. ENGINE->cursor().set(Cursor::Map::POINTER);
  558. ESpellCastProblem spellCastProblem = owner.getBattle()->battleCanCastSpell(myHero, spells::Mode::HERO);
  559. if(spellCastProblem == ESpellCastProblem::OK)
  560. {
  561. ENGINE->windows().createAndPushWindow<CSpellWindow>(myHero, owner.curInt.get());
  562. }
  563. else if (spellCastProblem == ESpellCastProblem::MAGIC_IS_BLOCKED)
  564. {
  565. //TODO: move to spell mechanics, add more information to spell cast problem
  566. //Handle Orb of Inhibition-like effects -> we want to display dialog with info, why casting is impossible
  567. auto blockingBonus = owner.currentHero()->getFirstBonus(Selector::type()(BonusType::BLOCK_ALL_MAGIC));
  568. if (!blockingBonus)
  569. return;
  570. if (blockingBonus->source == BonusSource::ARTIFACT)
  571. {
  572. const auto artID = blockingBonus->sid.as<ArtifactID>();
  573. //If we have artifact, put name of our hero. Otherwise assume it's the enemy.
  574. //TODO check who *really* is source of bonus
  575. std::string heroName = myHero->hasArt(artID, true) ? myHero->getNameTranslated() : owner.enemyHero().name;
  576. //%s wields the %s, an ancient artifact which creates a p dead to all magic.
  577. GAME->interface()->showInfoDialog(boost::str(boost::format(LIBRARY->generaltexth->allTexts[683])
  578. % heroName % LIBRARY->artifacts()->getByIndex(artID)->getNameTranslated()));
  579. }
  580. else if(blockingBonus->source == BonusSource::OBJECT_TYPE)
  581. {
  582. if(blockingBonus->sid.as<MapObjectID>() == Obj::GARRISON || blockingBonus->sid.as<MapObjectID>() == Obj::GARRISON2)
  583. GAME->interface()->showInfoDialog(LIBRARY->generaltexth->allTexts[684]);
  584. }
  585. }
  586. else
  587. {
  588. logGlobal->warn("Unexpected problem with readiness to cast spell");
  589. }
  590. }
  591. void BattleWindow::bWaitf()
  592. {
  593. if (owner.actionsController->heroSpellcastingModeActive())
  594. return;
  595. if (owner.stacksController->getActiveStack() != nullptr)
  596. owner.giveCommand(EActionType::WAIT);
  597. }
  598. void BattleWindow::bDefencef()
  599. {
  600. if (owner.actionsController->heroSpellcastingModeActive())
  601. return;
  602. if (owner.stacksController->getActiveStack() != nullptr)
  603. owner.giveCommand(EActionType::DEFEND);
  604. }
  605. void BattleWindow::bConsoleUpf()
  606. {
  607. if (owner.actionsController->heroSpellcastingModeActive())
  608. return;
  609. console->scrollUp();
  610. }
  611. void BattleWindow::bConsoleDownf()
  612. {
  613. if (owner.actionsController->heroSpellcastingModeActive())
  614. return;
  615. console->scrollDown();
  616. }
  617. void BattleWindow::bTacticNextStack()
  618. {
  619. owner.tacticNextStack(nullptr);
  620. }
  621. void BattleWindow::bTacticPhaseEnd()
  622. {
  623. owner.tacticPhaseEnd();
  624. }
  625. void BattleWindow::blockUI(bool on)
  626. {
  627. bool canCastSpells = false;
  628. auto hero = owner.getBattle()->battleGetMyHero();
  629. if(hero)
  630. {
  631. ESpellCastProblem spellcastingProblem = owner.getBattle()->battleCanCastSpell(hero, spells::Mode::HERO);
  632. //if magic is blocked, we leave button active, so the message can be displayed after button click
  633. canCastSpells = spellcastingProblem == ESpellCastProblem::OK || spellcastingProblem == ESpellCastProblem::MAGIC_IS_BLOCKED;
  634. }
  635. bool canWait = owner.stacksController->getActiveStack() ? !owner.stacksController->getActiveStack()->waitedThisTurn : false;
  636. setShortcutBlocked(EShortcut::GLOBAL_OPTIONS, on);
  637. setShortcutBlocked(EShortcut::BATTLE_OPEN_ACTIVE_UNIT, on);
  638. setShortcutBlocked(EShortcut::BATTLE_OPEN_HOVERED_UNIT, on);
  639. setShortcutBlocked(EShortcut::BATTLE_RETREAT, on || !owner.getBattle()->battleCanFlee());
  640. setShortcutBlocked(EShortcut::BATTLE_SURRENDER, on || owner.getBattle()->battleGetSurrenderCost() < 0);
  641. setShortcutBlocked(EShortcut::BATTLE_CAST_SPELL, on || owner.tacticsMode || !canCastSpells);
  642. setShortcutBlocked(EShortcut::BATTLE_WAIT, on || owner.tacticsMode || !canWait);
  643. setShortcutBlocked(EShortcut::BATTLE_DEFEND, on || owner.tacticsMode);
  644. setShortcutBlocked(EShortcut::BATTLE_AUTOCOMBAT, (settings["battle"]["endWithAutocombat"].Bool() && onlyOnePlayerHuman) ? on || owner.tacticsMode || owner.actionsController->heroSpellcastingModeActive() : owner.actionsController->heroSpellcastingModeActive());
  645. setShortcutBlocked(EShortcut::BATTLE_END_WITH_AUTOCOMBAT, on || !onlyOnePlayerHuman || owner.actionsController->heroSpellcastingModeActive());
  646. setShortcutBlocked(EShortcut::BATTLE_TACTICS_END, on || !owner.tacticsMode);
  647. setShortcutBlocked(EShortcut::BATTLE_TACTICS_NEXT, on || !owner.tacticsMode);
  648. setShortcutBlocked(EShortcut::BATTLE_CONSOLE_DOWN, on && !owner.tacticsMode);
  649. setShortcutBlocked(EShortcut::BATTLE_CONSOLE_UP, on && !owner.tacticsMode);
  650. quickSpellWindow->setInputEnabled(!on);
  651. unitActionWindow->setInputEnabled(!on);
  652. }
  653. void BattleWindow::bOpenActiveUnit()
  654. {
  655. const auto * unit = owner.stacksController->getActiveStack();
  656. if (unit)
  657. ENGINE->windows().createAndPushWindow<CStackWindow>(unit, false);
  658. }
  659. void BattleWindow::bOpenHoveredUnit()
  660. {
  661. const auto units = owner.stacksController->getHoveredStacksUnitIds();
  662. if (!units.empty())
  663. {
  664. const auto * unit = owner.getBattle()->battleGetStackByID(units[0]);
  665. if (unit)
  666. ENGINE->windows().createAndPushWindow<CStackWindow>(unit, false);
  667. }
  668. }
  669. std::optional<uint32_t> BattleWindow::getQueueHoveredUnitId()
  670. {
  671. return queue->getHoveredUnitIdIfAny();
  672. }
  673. void BattleWindow::endWithAutocombat()
  674. {
  675. if(!owner.makingTurn())
  676. return;
  677. GAME->interface()->showYesNoDialog(
  678. LIBRARY->generaltexth->translate("vcmi.battleWindow.endWithAutocombat"),
  679. [this]()
  680. {
  681. owner.curInt->isAutoFightEndBattle = true;
  682. auto ai = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  683. AutocombatPreferences autocombatPreferences = AutocombatPreferences();
  684. autocombatPreferences.enableSpellsUsage = settings["battle"]["enableAutocombatSpells"].Bool();
  685. ai->initBattleInterface(owner.curInt->env, owner.curInt->cb, autocombatPreferences);
  686. ai->battleStart(owner.getBattleID(), owner.army1, owner.army2, int3(0,0,0), owner.attackingHeroInstance, owner.defendingHeroInstance, owner.getBattle()->battleGetMySide(), false);
  687. owner.curInt->isAutoFightOn = true;
  688. owner.curInt->registerBattleInterface(ai);
  689. owner.requestAutofightingAIToTakeAction();
  690. close();
  691. owner.curInt->battleInt.reset();
  692. },
  693. nullptr
  694. );
  695. }
  696. void BattleWindow::showAll(Canvas & to)
  697. {
  698. CIntObject::showAll(to);
  699. if (ENGINE->screenDimensions().x != 800 || ENGINE->screenDimensions().y !=600)
  700. CMessage::drawBorder(owner.curInt->playerID, to, pos.w+28, pos.h+29, pos.x-14, pos.y-15);
  701. }
  702. void BattleWindow::show(Canvas & to)
  703. {
  704. CIntObject::show(to);
  705. GAME->interface()->cingconsole->show(to);
  706. }
  707. void BattleWindow::close()
  708. {
  709. if(!ENGINE->windows().isTopWindow(this))
  710. logGlobal->error("Only top interface must be closed");
  711. ENGINE->windows().popWindows(1);
  712. }