BattleWindow.cpp 28 KB

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