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