BattleWindow.cpp 17 KB

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