2
0

BattleWindow.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 "../adventureMap/CInGameConsole.h"
  31. #include "../../CCallback.h"
  32. #include "../../lib/CGeneralTextHandler.h"
  33. #include "../../lib/gameState/InfoAboutArmy.h"
  34. #include "../../lib/mapObjects/CGHeroInstance.h"
  35. #include "../../lib/CStack.h"
  36. #include "../../lib/CConfigHandler.h"
  37. #include "../../lib/filesystem/ResourceID.h"
  38. #include "../windows/settings/SettingsMainWindow.h"
  39. BattleWindow::BattleWindow(BattleInterface & owner):
  40. owner(owner),
  41. defaultAction(PossiblePlayerBattleAction::INVALID)
  42. {
  43. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  44. pos.w = 800;
  45. pos.h = 600;
  46. pos = center();
  47. REGISTER_BUILDER("battleConsole", &BattleWindow::buildBattleConsole);
  48. const JsonNode config(ResourceID("config/widgets/BattleWindow.json"));
  49. addShortcut(EShortcut::GLOBAL_OPTIONS, std::bind(&BattleWindow::bOptionsf, this));
  50. addShortcut(EShortcut::BATTLE_SURRENDER, std::bind(&BattleWindow::bSurrenderf, this));
  51. addShortcut(EShortcut::BATTLE_RETREAT, std::bind(&BattleWindow::bFleef, this));
  52. addShortcut(EShortcut::BATTLE_AUTOCOMBAT, std::bind(&BattleWindow::bAutofightf, this));
  53. addShortcut(EShortcut::BATTLE_CAST_SPELL, std::bind(&BattleWindow::bSpellf, this));
  54. addShortcut(EShortcut::BATTLE_WAIT, std::bind(&BattleWindow::bWaitf, this));
  55. addShortcut(EShortcut::BATTLE_DEFEND, std::bind(&BattleWindow::bDefencef, this));
  56. addShortcut(EShortcut::BATTLE_CONSOLE_UP, std::bind(&BattleWindow::bConsoleUpf, this));
  57. addShortcut(EShortcut::BATTLE_CONSOLE_DOWN, std::bind(&BattleWindow::bConsoleDownf, this));
  58. addShortcut(EShortcut::BATTLE_TACTICS_NEXT, std::bind(&BattleWindow::bTacticNextStack, this));
  59. addShortcut(EShortcut::BATTLE_TACTICS_END, std::bind(&BattleWindow::bTacticPhaseEnd, this));
  60. addShortcut(EShortcut::BATTLE_SELECT_ACTION, std::bind(&BattleWindow::bSwitchActionf, this));
  61. addShortcut(EShortcut::BATTLE_TOGGLE_QUEUE, [this](){ this->toggleQueueVisibility();});
  62. addShortcut(EShortcut::BATTLE_USE_CREATURE_SPELL, [this](){ this->owner.actionsController->enterCreatureCastingMode(); });
  63. addShortcut(EShortcut::GLOBAL_CANCEL, [this](){ this->owner.actionsController->endCastingSpell(); });
  64. build(config);
  65. console = widget<BattleConsole>("console");
  66. owner.console = console;
  67. owner.fieldController.reset( new BattleFieldController(owner));
  68. owner.fieldController->createHeroes();
  69. createQueue();
  70. if ( owner.tacticsMode )
  71. tacticPhaseStarted();
  72. else
  73. tacticPhaseEnded();
  74. addUsedEvents(LCLICK | KEYBOARD);
  75. }
  76. void BattleWindow::createQueue()
  77. {
  78. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  79. //create stack queue and adjust our own position
  80. bool embedQueue;
  81. bool showQueue = settings["battle"]["showQueue"].Bool();
  82. std::string queueSize = settings["battle"]["queueSize"].String();
  83. if(queueSize == "auto")
  84. embedQueue = GH.screenDimensions().y < 700;
  85. else
  86. embedQueue = GH.screenDimensions().y < 700 || queueSize == "small";
  87. queue = std::make_shared<StackQueue>(embedQueue, owner);
  88. if(!embedQueue && showQueue)
  89. {
  90. //re-center, taking into account stack queue position
  91. pos.y -= queue->pos.h;
  92. pos.h += queue->pos.h;
  93. pos = center();
  94. }
  95. if (!showQueue)
  96. queue->disable();
  97. }
  98. BattleWindow::~BattleWindow()
  99. {
  100. CPlayerInterface::battleInt = nullptr;
  101. }
  102. std::shared_ptr<BattleConsole> BattleWindow::buildBattleConsole(const JsonNode & config) const
  103. {
  104. auto rect = readRect(config["rect"]);
  105. auto offset = readPosition(config["imagePosition"]);
  106. auto background = widget<CPicture>("menuBattle");
  107. return std::make_shared<BattleConsole>(background, rect.topLeft(), offset, rect.dimensions() );
  108. }
  109. void BattleWindow::toggleQueueVisibility()
  110. {
  111. if(settings["battle"]["showQueue"].Bool())
  112. hideQueue();
  113. else
  114. showQueue();
  115. }
  116. void BattleWindow::hideQueue()
  117. {
  118. if(settings["battle"]["showQueue"].Bool() == false)
  119. return;
  120. Settings showQueue = settings.write["battle"]["showQueue"];
  121. showQueue->Bool() = false;
  122. queue->disable();
  123. if (!queue->embedded)
  124. {
  125. //re-center, taking into account stack queue position
  126. pos.y += queue->pos.h;
  127. pos.h -= queue->pos.h;
  128. pos = center();
  129. }
  130. GH.windows().totalRedraw();
  131. }
  132. void BattleWindow::showQueue()
  133. {
  134. if(settings["battle"]["showQueue"].Bool() == true)
  135. return;
  136. Settings showQueue = settings.write["battle"]["showQueue"];
  137. showQueue->Bool() = true;
  138. createQueue();
  139. updateQueue();
  140. GH.windows().totalRedraw();
  141. }
  142. void BattleWindow::updateQueue()
  143. {
  144. queue->update();
  145. }
  146. void BattleWindow::activate()
  147. {
  148. GH.setStatusbar(console);
  149. CIntObject::activate();
  150. LOCPLINT->cingconsole->activate();
  151. }
  152. void BattleWindow::deactivate()
  153. {
  154. GH.setStatusbar(nullptr);
  155. CIntObject::deactivate();
  156. LOCPLINT->cingconsole->deactivate();
  157. }
  158. bool BattleWindow::captureThisKey(EShortcut key)
  159. {
  160. return owner.openingPlaying();
  161. }
  162. void BattleWindow::keyPressed(EShortcut key)
  163. {
  164. if (owner.openingPlaying())
  165. {
  166. owner.openingEnd();
  167. return;
  168. }
  169. InterfaceObjectConfigurable::keyPressed(key);
  170. }
  171. void BattleWindow::clickPressed(const Point & cursorPosition)
  172. {
  173. if (owner.openingPlaying())
  174. {
  175. owner.openingEnd();
  176. return;
  177. }
  178. InterfaceObjectConfigurable::clickPressed(cursorPosition);
  179. }
  180. void BattleWindow::tacticPhaseStarted()
  181. {
  182. auto menuBattle = widget<CIntObject>("menuBattle");
  183. auto console = widget<CIntObject>("console");
  184. auto menuTactics = widget<CIntObject>("menuTactics");
  185. auto tacticNext = widget<CIntObject>("tacticNext");
  186. auto tacticEnd = widget<CIntObject>("tacticEnd");
  187. auto alternativeAction = widget<CIntObject>("alternativeAction");
  188. menuBattle->disable();
  189. console->disable();
  190. if (alternativeAction)
  191. alternativeAction->disable();
  192. menuTactics->enable();
  193. tacticNext->enable();
  194. tacticEnd->enable();
  195. redraw();
  196. }
  197. void BattleWindow::tacticPhaseEnded()
  198. {
  199. auto menuBattle = widget<CIntObject>("menuBattle");
  200. auto console = widget<CIntObject>("console");
  201. auto menuTactics = widget<CIntObject>("menuTactics");
  202. auto tacticNext = widget<CIntObject>("tacticNext");
  203. auto tacticEnd = widget<CIntObject>("tacticEnd");
  204. auto alternativeAction = widget<CIntObject>("alternativeAction");
  205. menuBattle->enable();
  206. console->enable();
  207. if (alternativeAction)
  208. alternativeAction->enable();
  209. menuTactics->disable();
  210. tacticNext->disable();
  211. tacticEnd->disable();
  212. redraw();
  213. }
  214. void BattleWindow::bOptionsf()
  215. {
  216. if (owner.actionsController->spellcastingModeActive())
  217. return;
  218. CCS->curh->set(Cursor::Map::POINTER);
  219. GH.windows().createAndPushWindow<SettingsMainWindow>(&owner);
  220. }
  221. void BattleWindow::bSurrenderf()
  222. {
  223. if (owner.actionsController->spellcastingModeActive())
  224. return;
  225. int cost = owner.curInt->cb->battleGetSurrenderCost();
  226. if(cost >= 0)
  227. {
  228. std::string enemyHeroName = owner.curInt->cb->battleGetEnemyHero().name;
  229. if(enemyHeroName.empty())
  230. {
  231. logGlobal->warn("Surrender performed without enemy hero, should not happen!");
  232. enemyHeroName = "#ENEMY#";
  233. }
  234. 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."
  235. owner.curInt->showYesNoDialog(surrenderMessage, [this](){ reallySurrender(); }, nullptr);
  236. }
  237. }
  238. void BattleWindow::bFleef()
  239. {
  240. if (owner.actionsController->spellcastingModeActive())
  241. return;
  242. if ( owner.curInt->cb->battleCanFlee() )
  243. {
  244. CFunctionList<void()> ony = std::bind(&BattleWindow::reallyFlee,this);
  245. owner.curInt->showYesNoDialog(CGI->generaltexth->allTexts[28], ony, nullptr); //Are you sure you want to retreat?
  246. }
  247. else
  248. {
  249. std::vector<std::shared_ptr<CComponent>> comps;
  250. std::string heroName;
  251. //calculating fleeing hero's name
  252. if (owner.attackingHeroInstance)
  253. if (owner.attackingHeroInstance->tempOwner == owner.curInt->cb->getMyColor())
  254. heroName = owner.attackingHeroInstance->getNameTranslated();
  255. if (owner.defendingHeroInstance)
  256. if (owner.defendingHeroInstance->tempOwner == owner.curInt->cb->getMyColor())
  257. heroName = owner.defendingHeroInstance->getNameTranslated();
  258. //calculating text
  259. auto txt = boost::format(CGI->generaltexth->allTexts[340]) % heroName; //The Shackles of War are present. %s can not retreat!
  260. //printing message
  261. owner.curInt->showInfoDialog(boost::to_string(txt), comps);
  262. }
  263. }
  264. void BattleWindow::reallyFlee()
  265. {
  266. owner.giveCommand(EActionType::RETREAT);
  267. CCS->curh->set(Cursor::Map::POINTER);
  268. }
  269. void BattleWindow::reallySurrender()
  270. {
  271. if (owner.curInt->cb->getResourceAmount(EGameResID::GOLD) < owner.curInt->cb->battleGetSurrenderCost())
  272. {
  273. owner.curInt->showInfoDialog(CGI->generaltexth->allTexts[29]); //You don't have enough gold!
  274. }
  275. else
  276. {
  277. owner.giveCommand(EActionType::SURRENDER);
  278. CCS->curh->set(Cursor::Map::POINTER);
  279. }
  280. }
  281. void BattleWindow::showAlternativeActionIcon(PossiblePlayerBattleAction action)
  282. {
  283. auto w = widget<CButton>("alternativeAction");
  284. if(!w)
  285. return;
  286. std::string iconName = variables["actionIconDefault"].String();
  287. switch(action.get())
  288. {
  289. case PossiblePlayerBattleAction::ATTACK:
  290. iconName = variables["actionIconAttack"].String();
  291. break;
  292. case PossiblePlayerBattleAction::SHOOT:
  293. iconName = variables["actionIconShoot"].String();
  294. break;
  295. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  296. iconName = variables["actionIconSpell"].String();
  297. break;
  298. //TODO: figure out purpose of this icon
  299. //case PossiblePlayerBattleAction::???:
  300. //iconName = variables["actionIconWalk"].String();
  301. //break;
  302. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  303. iconName = variables["actionIconReturn"].String();
  304. break;
  305. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  306. iconName = variables["actionIconNoReturn"].String();
  307. break;
  308. }
  309. auto anim = std::make_shared<CAnimation>(iconName);
  310. w->setImage(anim);
  311. w->redraw();
  312. }
  313. void BattleWindow::setAlternativeActions(const std::list<PossiblePlayerBattleAction> & actions)
  314. {
  315. alternativeActions = actions;
  316. defaultAction = PossiblePlayerBattleAction::INVALID;
  317. if(alternativeActions.size() > 1)
  318. defaultAction = alternativeActions.back();
  319. if(!alternativeActions.empty())
  320. showAlternativeActionIcon(alternativeActions.front());
  321. else
  322. showAlternativeActionIcon(defaultAction);
  323. }
  324. void BattleWindow::bAutofightf()
  325. {
  326. if (owner.actionsController->spellcastingModeActive())
  327. return;
  328. //Stop auto-fight mode
  329. if(owner.curInt->isAutoFightOn)
  330. {
  331. assert(owner.curInt->autofightingAI);
  332. owner.curInt->isAutoFightOn = false;
  333. logGlobal->trace("Stopping the autofight...");
  334. }
  335. else if(!owner.curInt->autofightingAI)
  336. {
  337. owner.curInt->isAutoFightOn = true;
  338. blockUI(true);
  339. auto ai = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  340. ai->initBattleInterface(owner.curInt->env, owner.curInt->cb);
  341. ai->battleStart(owner.army1, owner.army2, int3(0,0,0), owner.attackingHeroInstance, owner.defendingHeroInstance, owner.curInt->cb->battleGetMySide());
  342. owner.curInt->autofightingAI = ai;
  343. owner.curInt->cb->registerBattleInterface(ai);
  344. owner.requestAutofightingAIToTakeAction();
  345. }
  346. }
  347. void BattleWindow::bSpellf()
  348. {
  349. if (owner.actionsController->spellcastingModeActive())
  350. return;
  351. if (!owner.makingTurn())
  352. return;
  353. auto myHero = owner.currentHero();
  354. if(!myHero)
  355. return;
  356. CCS->curh->set(Cursor::Map::POINTER);
  357. ESpellCastProblem::ESpellCastProblem spellCastProblem = owner.curInt->cb->battleCanCastSpell(myHero, spells::Mode::HERO);
  358. if(spellCastProblem == ESpellCastProblem::OK)
  359. {
  360. GH.windows().createAndPushWindow<CSpellWindow>(myHero, owner.curInt.get());
  361. }
  362. else if (spellCastProblem == ESpellCastProblem::MAGIC_IS_BLOCKED)
  363. {
  364. //TODO: move to spell mechanics, add more information to spell cast problem
  365. //Handle Orb of Inhibition-like effects -> we want to display dialog with info, why casting is impossible
  366. auto blockingBonus = owner.currentHero()->getBonusLocalFirst(Selector::type()(BonusType::BLOCK_ALL_MAGIC));
  367. if (!blockingBonus)
  368. return;
  369. if (blockingBonus->source == BonusSource::ARTIFACT)
  370. {
  371. const auto artID = ArtifactID(blockingBonus->sid);
  372. //If we have artifact, put name of our hero. Otherwise assume it's the enemy.
  373. //TODO check who *really* is source of bonus
  374. std::string heroName = myHero->hasArt(artID) ? myHero->getNameTranslated() : owner.enemyHero().name;
  375. //%s wields the %s, an ancient artifact which creates a p dead to all magic.
  376. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[683])
  377. % heroName % CGI->artifacts()->getByIndex(artID)->getNameTranslated()));
  378. }
  379. }
  380. }
  381. void BattleWindow::bSwitchActionf()
  382. {
  383. if(alternativeActions.empty())
  384. return;
  385. if(alternativeActions.front() == defaultAction)
  386. {
  387. alternativeActions.push_back(alternativeActions.front());
  388. alternativeActions.pop_front();
  389. }
  390. auto actions = owner.actionsController->getPossibleActions();
  391. if(!actions.empty() && actions.front() == alternativeActions.front())
  392. {
  393. owner.actionsController->removePossibleAction(alternativeActions.front());
  394. showAlternativeActionIcon(defaultAction);
  395. }
  396. else
  397. {
  398. owner.actionsController->pushFrontPossibleAction(alternativeActions.front());
  399. showAlternativeActionIcon(alternativeActions.front());
  400. }
  401. alternativeActions.push_back(alternativeActions.front());
  402. alternativeActions.pop_front();
  403. }
  404. void BattleWindow::bWaitf()
  405. {
  406. if (owner.actionsController->spellcastingModeActive())
  407. return;
  408. if (owner.stacksController->getActiveStack() != nullptr)
  409. owner.giveCommand(EActionType::WAIT);
  410. }
  411. void BattleWindow::bDefencef()
  412. {
  413. if (owner.actionsController->spellcastingModeActive())
  414. return;
  415. if (owner.stacksController->getActiveStack() != nullptr)
  416. owner.giveCommand(EActionType::DEFEND);
  417. }
  418. void BattleWindow::bConsoleUpf()
  419. {
  420. if (owner.actionsController->spellcastingModeActive())
  421. return;
  422. console->scrollUp();
  423. }
  424. void BattleWindow::bConsoleDownf()
  425. {
  426. if (owner.actionsController->spellcastingModeActive())
  427. return;
  428. console->scrollDown();
  429. }
  430. void BattleWindow::bTacticNextStack()
  431. {
  432. owner.tacticNextStack(nullptr);
  433. }
  434. void BattleWindow::bTacticPhaseEnd()
  435. {
  436. owner.tacticPhaseEnd();
  437. }
  438. void BattleWindow::blockUI(bool on)
  439. {
  440. bool canCastSpells = false;
  441. auto hero = owner.curInt->cb->battleGetMyHero();
  442. if(hero)
  443. {
  444. ESpellCastProblem::ESpellCastProblem spellcastingProblem = owner.curInt->cb->battleCanCastSpell(hero, spells::Mode::HERO);
  445. //if magic is blocked, we leave button active, so the message can be displayed after button click
  446. canCastSpells = spellcastingProblem == ESpellCastProblem::OK || spellcastingProblem == ESpellCastProblem::MAGIC_IS_BLOCKED;
  447. }
  448. bool canWait = owner.stacksController->getActiveStack() ? !owner.stacksController->getActiveStack()->waitedThisTurn : false;
  449. setShortcutBlocked(EShortcut::GLOBAL_OPTIONS, on);
  450. setShortcutBlocked(EShortcut::BATTLE_RETREAT, on || !owner.curInt->cb->battleCanFlee());
  451. setShortcutBlocked(EShortcut::BATTLE_SURRENDER, on || owner.curInt->cb->battleGetSurrenderCost() < 0);
  452. setShortcutBlocked(EShortcut::BATTLE_CAST_SPELL, on || owner.tacticsMode || !canCastSpells);
  453. setShortcutBlocked(EShortcut::BATTLE_WAIT, on || owner.tacticsMode || !canWait);
  454. setShortcutBlocked(EShortcut::BATTLE_DEFEND, on || owner.tacticsMode);
  455. setShortcutBlocked(EShortcut::BATTLE_SELECT_ACTION, on || owner.tacticsMode);
  456. setShortcutBlocked(EShortcut::BATTLE_AUTOCOMBAT, owner.actionsController->spellcastingModeActive());
  457. setShortcutBlocked(EShortcut::BATTLE_TACTICS_END, on && owner.tacticsMode);
  458. setShortcutBlocked(EShortcut::BATTLE_TACTICS_NEXT, on && owner.tacticsMode);
  459. setShortcutBlocked(EShortcut::BATTLE_CONSOLE_DOWN, on && !owner.tacticsMode);
  460. setShortcutBlocked(EShortcut::BATTLE_CONSOLE_UP, on && !owner.tacticsMode);
  461. }
  462. std::optional<uint32_t> BattleWindow::getQueueHoveredUnitId()
  463. {
  464. return queue->getHoveredUnitIdIfAny();
  465. }
  466. void BattleWindow::showAll(Canvas & to)
  467. {
  468. CIntObject::showAll(to);
  469. if (GH.screenDimensions().x != 800 || GH.screenDimensions().y !=600)
  470. CMessage::drawBorder(owner.curInt->playerID, to.getInternalSurface(), pos.w+28, pos.h+29, pos.x-14, pos.y-15);
  471. }
  472. void BattleWindow::show(Canvas & to)
  473. {
  474. CIntObject::show(to);
  475. LOCPLINT->cingconsole->show(to);
  476. }
  477. void BattleWindow::close()
  478. {
  479. if(!GH.windows().isTopWindow(this))
  480. logGlobal->error("Only top interface must be closed");
  481. GH.windows().popWindows(1);
  482. }