BattleWindow.cpp 17 KB

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