BattleWindow.cpp 17 KB

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