BattleWindow.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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.statusbar = console;
  148. CIntObject::activate();
  149. LOCPLINT->cingconsole->activate();
  150. }
  151. void BattleWindow::deactivate()
  152. {
  153. CIntObject::deactivate();
  154. LOCPLINT->cingconsole->deactivate();
  155. }
  156. bool BattleWindow::captureThisKey(EShortcut key)
  157. {
  158. return owner.openingPlaying();
  159. }
  160. void BattleWindow::keyPressed(EShortcut key)
  161. {
  162. if (owner.openingPlaying())
  163. {
  164. owner.openingEnd();
  165. return;
  166. }
  167. InterfaceObjectConfigurable::keyPressed(key);
  168. }
  169. void BattleWindow::clickRight(tribool down, bool previousState)
  170. {
  171. if (!down)
  172. owner.actionsController->endCastingSpell();
  173. }
  174. void BattleWindow::tacticPhaseStarted()
  175. {
  176. auto menuBattle = widget<CIntObject>("menuBattle");
  177. auto console = widget<CIntObject>("console");
  178. auto menuTactics = widget<CIntObject>("menuTactics");
  179. auto tacticNext = widget<CIntObject>("tacticNext");
  180. auto tacticEnd = widget<CIntObject>("tacticEnd");
  181. auto alternativeAction = widget<CIntObject>("alternativeAction");
  182. menuBattle->disable();
  183. console->disable();
  184. if (alternativeAction)
  185. alternativeAction->disable();
  186. menuTactics->enable();
  187. tacticNext->enable();
  188. tacticEnd->enable();
  189. redraw();
  190. }
  191. void BattleWindow::tacticPhaseEnded()
  192. {
  193. auto menuBattle = widget<CIntObject>("menuBattle");
  194. auto console = widget<CIntObject>("console");
  195. auto menuTactics = widget<CIntObject>("menuTactics");
  196. auto tacticNext = widget<CIntObject>("tacticNext");
  197. auto tacticEnd = widget<CIntObject>("tacticEnd");
  198. auto alternativeAction = widget<CIntObject>("alternativeAction");
  199. menuBattle->enable();
  200. console->enable();
  201. if (alternativeAction)
  202. alternativeAction->enable();
  203. menuTactics->disable();
  204. tacticNext->disable();
  205. tacticEnd->disable();
  206. redraw();
  207. }
  208. void BattleWindow::bOptionsf()
  209. {
  210. if (owner.actionsController->spellcastingModeActive())
  211. return;
  212. CCS->curh->set(Cursor::Map::POINTER);
  213. GH.windows().pushIntT<SettingsMainWindow>(&owner);
  214. }
  215. void BattleWindow::bSurrenderf()
  216. {
  217. if (owner.actionsController->spellcastingModeActive())
  218. return;
  219. int cost = owner.curInt->cb->battleGetSurrenderCost();
  220. if(cost >= 0)
  221. {
  222. std::string enemyHeroName = owner.curInt->cb->battleGetEnemyHero().name;
  223. if(enemyHeroName.empty())
  224. {
  225. logGlobal->warn("Surrender performed without enemy hero, should not happen!");
  226. enemyHeroName = "#ENEMY#";
  227. }
  228. 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."
  229. owner.curInt->showYesNoDialog(surrenderMessage, [this](){ reallySurrender(); }, nullptr);
  230. }
  231. }
  232. void BattleWindow::bFleef()
  233. {
  234. if (owner.actionsController->spellcastingModeActive())
  235. return;
  236. if ( owner.curInt->cb->battleCanFlee() )
  237. {
  238. CFunctionList<void()> ony = std::bind(&BattleWindow::reallyFlee,this);
  239. owner.curInt->showYesNoDialog(CGI->generaltexth->allTexts[28], ony, nullptr); //Are you sure you want to retreat?
  240. }
  241. else
  242. {
  243. std::vector<std::shared_ptr<CComponent>> comps;
  244. std::string heroName;
  245. //calculating fleeing hero's name
  246. if (owner.attackingHeroInstance)
  247. if (owner.attackingHeroInstance->tempOwner == owner.curInt->cb->getMyColor())
  248. heroName = owner.attackingHeroInstance->getNameTranslated();
  249. if (owner.defendingHeroInstance)
  250. if (owner.defendingHeroInstance->tempOwner == owner.curInt->cb->getMyColor())
  251. heroName = owner.defendingHeroInstance->getNameTranslated();
  252. //calculating text
  253. auto txt = boost::format(CGI->generaltexth->allTexts[340]) % heroName; //The Shackles of War are present. %s can not retreat!
  254. //printing message
  255. owner.curInt->showInfoDialog(boost::to_string(txt), comps);
  256. }
  257. }
  258. void BattleWindow::reallyFlee()
  259. {
  260. owner.giveCommand(EActionType::RETREAT);
  261. CCS->curh->set(Cursor::Map::POINTER);
  262. }
  263. void BattleWindow::reallySurrender()
  264. {
  265. if (owner.curInt->cb->getResourceAmount(EGameResID::GOLD) < owner.curInt->cb->battleGetSurrenderCost())
  266. {
  267. owner.curInt->showInfoDialog(CGI->generaltexth->allTexts[29]); //You don't have enough gold!
  268. }
  269. else
  270. {
  271. owner.giveCommand(EActionType::SURRENDER);
  272. CCS->curh->set(Cursor::Map::POINTER);
  273. }
  274. }
  275. void BattleWindow::showAlternativeActionIcon(PossiblePlayerBattleAction action)
  276. {
  277. auto w = widget<CButton>("alternativeAction");
  278. if(!w)
  279. return;
  280. std::string iconName = variables["actionIconDefault"].String();
  281. switch(action.get())
  282. {
  283. case PossiblePlayerBattleAction::ATTACK:
  284. iconName = variables["actionIconAttack"].String();
  285. break;
  286. case PossiblePlayerBattleAction::SHOOT:
  287. iconName = variables["actionIconShoot"].String();
  288. break;
  289. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  290. iconName = variables["actionIconSpell"].String();
  291. break;
  292. //TODO: figure out purpose of this icon
  293. //case PossiblePlayerBattleAction::???:
  294. //iconName = variables["actionIconWalk"].String();
  295. //break;
  296. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  297. iconName = variables["actionIconReturn"].String();
  298. break;
  299. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  300. iconName = variables["actionIconNoReturn"].String();
  301. break;
  302. }
  303. auto anim = std::make_shared<CAnimation>(iconName);
  304. w->setImage(anim);
  305. w->redraw();
  306. }
  307. void BattleWindow::setAlternativeActions(const std::list<PossiblePlayerBattleAction> & actions)
  308. {
  309. alternativeActions = actions;
  310. defaultAction = PossiblePlayerBattleAction::INVALID;
  311. if(alternativeActions.size() > 1)
  312. defaultAction = alternativeActions.back();
  313. if(!alternativeActions.empty())
  314. showAlternativeActionIcon(alternativeActions.front());
  315. else
  316. showAlternativeActionIcon(defaultAction);
  317. }
  318. void BattleWindow::bAutofightf()
  319. {
  320. if (owner.actionsController->spellcastingModeActive())
  321. return;
  322. //Stop auto-fight mode
  323. if(owner.curInt->isAutoFightOn)
  324. {
  325. assert(owner.curInt->autofightingAI);
  326. owner.curInt->isAutoFightOn = false;
  327. logGlobal->trace("Stopping the autofight...");
  328. }
  329. else if(!owner.curInt->autofightingAI)
  330. {
  331. owner.curInt->isAutoFightOn = true;
  332. blockUI(true);
  333. auto ai = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  334. ai->initBattleInterface(owner.curInt->env, owner.curInt->cb);
  335. ai->battleStart(owner.army1, owner.army2, int3(0,0,0), owner.attackingHeroInstance, owner.defendingHeroInstance, owner.curInt->cb->battleGetMySide());
  336. owner.curInt->autofightingAI = ai;
  337. owner.curInt->cb->registerBattleInterface(ai);
  338. owner.requestAutofightingAIToTakeAction();
  339. }
  340. }
  341. void BattleWindow::bSpellf()
  342. {
  343. if (owner.actionsController->spellcastingModeActive())
  344. return;
  345. if (!owner.makingTurn())
  346. return;
  347. auto myHero = owner.currentHero();
  348. if(!myHero)
  349. return;
  350. CCS->curh->set(Cursor::Map::POINTER);
  351. ESpellCastProblem::ESpellCastProblem spellCastProblem = owner.curInt->cb->battleCanCastSpell(myHero, spells::Mode::HERO);
  352. if(spellCastProblem == ESpellCastProblem::OK)
  353. {
  354. GH.windows().pushIntT<CSpellWindow>(myHero, owner.curInt.get());
  355. }
  356. else if (spellCastProblem == ESpellCastProblem::MAGIC_IS_BLOCKED)
  357. {
  358. //TODO: move to spell mechanics, add more information to spell cast problem
  359. //Handle Orb of Inhibition-like effects -> we want to display dialog with info, why casting is impossible
  360. auto blockingBonus = owner.currentHero()->getBonusLocalFirst(Selector::type()(BonusType::BLOCK_ALL_MAGIC));
  361. if (!blockingBonus)
  362. return;
  363. if (blockingBonus->source == BonusSource::ARTIFACT)
  364. {
  365. const auto artID = ArtifactID(blockingBonus->sid);
  366. //If we have artifact, put name of our hero. Otherwise assume it's the enemy.
  367. //TODO check who *really* is source of bonus
  368. std::string heroName = myHero->hasArt(artID) ? myHero->getNameTranslated() : owner.enemyHero().name;
  369. //%s wields the %s, an ancient artifact which creates a p dead to all magic.
  370. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[683])
  371. % heroName % CGI->artifacts()->getByIndex(artID)->getNameTranslated()));
  372. }
  373. }
  374. }
  375. void BattleWindow::bSwitchActionf()
  376. {
  377. if(alternativeActions.empty())
  378. return;
  379. if(alternativeActions.front() == defaultAction)
  380. {
  381. alternativeActions.push_back(alternativeActions.front());
  382. alternativeActions.pop_front();
  383. }
  384. auto actions = owner.actionsController->getPossibleActions();
  385. if(!actions.empty() && actions.front() == alternativeActions.front())
  386. {
  387. owner.actionsController->removePossibleAction(alternativeActions.front());
  388. showAlternativeActionIcon(defaultAction);
  389. }
  390. else
  391. {
  392. owner.actionsController->pushFrontPossibleAction(alternativeActions.front());
  393. showAlternativeActionIcon(alternativeActions.front());
  394. }
  395. alternativeActions.push_back(alternativeActions.front());
  396. alternativeActions.pop_front();
  397. }
  398. void BattleWindow::bWaitf()
  399. {
  400. if (owner.actionsController->spellcastingModeActive())
  401. return;
  402. if (owner.stacksController->getActiveStack() != nullptr)
  403. owner.giveCommand(EActionType::WAIT);
  404. }
  405. void BattleWindow::bDefencef()
  406. {
  407. if (owner.actionsController->spellcastingModeActive())
  408. return;
  409. if (owner.stacksController->getActiveStack() != nullptr)
  410. owner.giveCommand(EActionType::DEFEND);
  411. }
  412. void BattleWindow::bConsoleUpf()
  413. {
  414. if (owner.actionsController->spellcastingModeActive())
  415. return;
  416. console->scrollUp();
  417. }
  418. void BattleWindow::bConsoleDownf()
  419. {
  420. if (owner.actionsController->spellcastingModeActive())
  421. return;
  422. console->scrollDown();
  423. }
  424. void BattleWindow::bTacticNextStack()
  425. {
  426. owner.tacticNextStack(nullptr);
  427. }
  428. void BattleWindow::bTacticPhaseEnd()
  429. {
  430. owner.tacticPhaseEnd();
  431. }
  432. void BattleWindow::blockUI(bool on)
  433. {
  434. bool canCastSpells = false;
  435. auto hero = owner.curInt->cb->battleGetMyHero();
  436. if(hero)
  437. {
  438. ESpellCastProblem::ESpellCastProblem spellcastingProblem = owner.curInt->cb->battleCanCastSpell(hero, spells::Mode::HERO);
  439. //if magic is blocked, we leave button active, so the message can be displayed after button click
  440. canCastSpells = spellcastingProblem == ESpellCastProblem::OK || spellcastingProblem == ESpellCastProblem::MAGIC_IS_BLOCKED;
  441. }
  442. bool canWait = owner.stacksController->getActiveStack() ? !owner.stacksController->getActiveStack()->waitedThisTurn : false;
  443. setShortcutBlocked(EShortcut::GLOBAL_OPTIONS, on);
  444. setShortcutBlocked(EShortcut::BATTLE_RETREAT, on || !owner.curInt->cb->battleCanFlee());
  445. setShortcutBlocked(EShortcut::BATTLE_SURRENDER, on || owner.curInt->cb->battleGetSurrenderCost() < 0);
  446. setShortcutBlocked(EShortcut::BATTLE_CAST_SPELL, on || owner.tacticsMode || !canCastSpells);
  447. setShortcutBlocked(EShortcut::BATTLE_WAIT, on || owner.tacticsMode || !canWait);
  448. setShortcutBlocked(EShortcut::BATTLE_DEFEND, on || owner.tacticsMode);
  449. setShortcutBlocked(EShortcut::BATTLE_SELECT_ACTION, on || owner.tacticsMode);
  450. setShortcutBlocked(EShortcut::BATTLE_AUTOCOMBAT, owner.actionsController->spellcastingModeActive());
  451. setShortcutBlocked(EShortcut::BATTLE_TACTICS_END, on && owner.tacticsMode);
  452. setShortcutBlocked(EShortcut::BATTLE_TACTICS_NEXT, on && owner.tacticsMode);
  453. setShortcutBlocked(EShortcut::BATTLE_CONSOLE_DOWN, on && !owner.tacticsMode);
  454. setShortcutBlocked(EShortcut::BATTLE_CONSOLE_UP, on && !owner.tacticsMode);
  455. }
  456. std::optional<uint32_t> BattleWindow::getQueueHoveredUnitId()
  457. {
  458. return queue->getHoveredUnitIdIfAny();
  459. }
  460. void BattleWindow::showAll(SDL_Surface *to)
  461. {
  462. CIntObject::showAll(to);
  463. if (GH.screenDimensions().x != 800 || GH.screenDimensions().y !=600)
  464. CMessage::drawBorder(owner.curInt->playerID, to, pos.w+28, pos.h+29, pos.x-14, pos.y-15);
  465. }
  466. void BattleWindow::show(SDL_Surface *to)
  467. {
  468. CIntObject::show(to);
  469. LOCPLINT->cingconsole->show(to);
  470. }
  471. void BattleWindow::close()
  472. {
  473. if(GH.windows().topInt().get() != this)
  474. logGlobal->error("Only top interface must be closed");
  475. GH.windows().popInts(1);
  476. }