BattleWindow.cpp 16 KB

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