BattleWindow.cpp 29 KB

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