BattleWindow.cpp 23 KB

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