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