BattleWindow.cpp 29 KB

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