BattleWindow.cpp 29 KB

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