BattleWindow.cpp 17 KB

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