BattleWindow.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. 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. //create stack queue and adjust our own position
  64. bool embedQueue;
  65. std::string queueSize = settings["battle"]["queueSize"].String();
  66. if(queueSize == "auto")
  67. embedQueue = GH.screenDimensions().y < 700;
  68. else
  69. embedQueue = GH.screenDimensions().y < 700 || queueSize == "small";
  70. queue = std::make_shared<StackQueue>(embedQueue, owner);
  71. if(!embedQueue && settings["battle"]["showQueue"].Bool())
  72. {
  73. //re-center, taking into account stack queue position
  74. pos.y -= queue->pos.h;
  75. pos.h += queue->pos.h;
  76. pos = center();
  77. }
  78. if ( owner.tacticsMode )
  79. tacticPhaseStarted();
  80. else
  81. tacticPhaseEnded();
  82. addUsedEvents(RCLICK | KEYBOARD);
  83. }
  84. BattleWindow::~BattleWindow()
  85. {
  86. CPlayerInterface::battleInt = nullptr;
  87. }
  88. std::shared_ptr<BattleConsole> BattleWindow::buildBattleConsole(const JsonNode & config) const
  89. {
  90. auto rect = readRect(config["rect"]);
  91. auto offset = readPosition(config["imagePosition"]);
  92. auto background = widget<CPicture>("menuBattle");
  93. return std::make_shared<BattleConsole>(background, rect.topLeft(), offset, rect.dimensions() );
  94. }
  95. void BattleWindow::hideQueue()
  96. {
  97. Settings showQueue = settings.write["battle"]["showQueue"];
  98. showQueue->Bool() = false;
  99. queue->disable();
  100. if (!queue->embedded)
  101. {
  102. //re-center, taking into account stack queue position
  103. pos.y += queue->pos.h;
  104. pos.h -= queue->pos.h;
  105. pos = center();
  106. GH.totalRedraw();
  107. }
  108. }
  109. void BattleWindow::showQueue()
  110. {
  111. Settings showQueue = settings.write["battle"]["showQueue"];
  112. showQueue->Bool() = true;
  113. queue->enable();
  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::updateQueue()
  124. {
  125. queue->update();
  126. }
  127. void BattleWindow::activate()
  128. {
  129. GH.statusbar = console;
  130. CIntObject::activate();
  131. LOCPLINT->cingconsole->activate();
  132. }
  133. void BattleWindow::deactivate()
  134. {
  135. CIntObject::deactivate();
  136. LOCPLINT->cingconsole->deactivate();
  137. }
  138. void BattleWindow::keyPressed(const SDL_Keycode & key)
  139. {
  140. if(key == SDLK_q)
  141. {
  142. if(settings["battle"]["showQueue"].Bool()) //hide queue
  143. hideQueue();
  144. else
  145. showQueue();
  146. }
  147. else if(key == SDLK_f)
  148. {
  149. owner.actionsController->enterCreatureCastingMode();
  150. }
  151. else if(key == SDLK_ESCAPE)
  152. {
  153. if(owner.getAnimationCondition(EAnimationEvents::OPENING) == true)
  154. CCS->soundh->stopSound(owner.battleIntroSoundChannel);
  155. else
  156. owner.actionsController->endCastingSpell();
  157. }
  158. }
  159. void BattleWindow::clickRight(tribool down, bool previousState)
  160. {
  161. if (!down)
  162. owner.actionsController->endCastingSpell();
  163. }
  164. void BattleWindow::tacticPhaseStarted()
  165. {
  166. auto menuBattle = widget<CIntObject>("menuBattle");
  167. auto console = widget<CIntObject>("console");
  168. auto menuTactics = widget<CIntObject>("menuTactics");
  169. auto tacticNext = widget<CIntObject>("tacticNext");
  170. auto tacticEnd = widget<CIntObject>("tacticEnd");
  171. menuBattle->disable();
  172. console->disable();
  173. menuTactics->enable();
  174. tacticNext->enable();
  175. tacticEnd->enable();
  176. redraw();
  177. }
  178. void BattleWindow::tacticPhaseEnded()
  179. {
  180. auto menuBattle = widget<CIntObject>("menuBattle");
  181. auto console = widget<CIntObject>("console");
  182. auto menuTactics = widget<CIntObject>("menuTactics");
  183. auto tacticNext = widget<CIntObject>("tacticNext");
  184. auto tacticEnd = widget<CIntObject>("tacticEnd");
  185. menuBattle->enable();
  186. console->enable();
  187. menuTactics->disable();
  188. tacticNext->disable();
  189. tacticEnd->disable();
  190. redraw();
  191. }
  192. void BattleWindow::bOptionsf()
  193. {
  194. if (owner.actionsController->spellcastingModeActive())
  195. return;
  196. CCS->curh->set(Cursor::Map::POINTER);
  197. GH.pushIntT<BattleOptionsWindow>(&owner);
  198. }
  199. void BattleWindow::bSurrenderf()
  200. {
  201. if (owner.actionsController->spellcastingModeActive())
  202. return;
  203. int cost = owner.curInt->cb->battleGetSurrenderCost();
  204. if(cost >= 0)
  205. {
  206. std::string enemyHeroName = owner.curInt->cb->battleGetEnemyHero().name;
  207. if(enemyHeroName.empty())
  208. {
  209. logGlobal->warn("Surrender performed without enemy hero, should not happen!");
  210. enemyHeroName = "#ENEMY#";
  211. }
  212. 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."
  213. owner.curInt->showYesNoDialog(surrenderMessage, [this](){ reallySurrender(); }, nullptr);
  214. }
  215. }
  216. void BattleWindow::bFleef()
  217. {
  218. if (owner.actionsController->spellcastingModeActive())
  219. return;
  220. if ( owner.curInt->cb->battleCanFlee() )
  221. {
  222. CFunctionList<void()> ony = std::bind(&BattleWindow::reallyFlee,this);
  223. owner.curInt->showYesNoDialog(CGI->generaltexth->allTexts[28], ony, nullptr); //Are you sure you want to retreat?
  224. }
  225. else
  226. {
  227. std::vector<std::shared_ptr<CComponent>> comps;
  228. std::string heroName;
  229. //calculating fleeing hero's name
  230. if (owner.attackingHeroInstance)
  231. if (owner.attackingHeroInstance->tempOwner == owner.curInt->cb->getMyColor())
  232. heroName = owner.attackingHeroInstance->getNameTranslated();
  233. if (owner.defendingHeroInstance)
  234. if (owner.defendingHeroInstance->tempOwner == owner.curInt->cb->getMyColor())
  235. heroName = owner.defendingHeroInstance->getNameTranslated();
  236. //calculating text
  237. auto txt = boost::format(CGI->generaltexth->allTexts[340]) % heroName; //The Shackles of War are present. %s can not retreat!
  238. //printing message
  239. owner.curInt->showInfoDialog(boost::to_string(txt), comps);
  240. }
  241. }
  242. void BattleWindow::reallyFlee()
  243. {
  244. owner.giveCommand(EActionType::RETREAT);
  245. CCS->curh->set(Cursor::Map::POINTER);
  246. }
  247. void BattleWindow::reallySurrender()
  248. {
  249. if (owner.curInt->cb->getResourceAmount(Res::GOLD) < owner.curInt->cb->battleGetSurrenderCost())
  250. {
  251. owner.curInt->showInfoDialog(CGI->generaltexth->allTexts[29]); //You don't have enough gold!
  252. }
  253. else
  254. {
  255. owner.giveCommand(EActionType::SURRENDER);
  256. CCS->curh->set(Cursor::Map::POINTER);
  257. }
  258. }
  259. void BattleWindow::showAlternativeActionIcon(PossiblePlayerBattleAction action)
  260. {
  261. auto w = widget<CButton>("alternativeAction");
  262. if(!w)
  263. return;
  264. std::string iconName = variables["actionIconDefault"].String();
  265. switch(action)
  266. {
  267. case PossiblePlayerBattleAction::ATTACK:
  268. iconName = variables["actionIconAttack"].String();
  269. break;
  270. case PossiblePlayerBattleAction::SHOOT:
  271. iconName = variables["actionIconShoot"].String();
  272. break;
  273. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  274. iconName = variables["actionIconSpell"].String();
  275. break;
  276. //TODO: figure out purpose of this icon
  277. //case PossiblePlayerBattleAction::???:
  278. //iconName = variables["actionIconWalk"].String();
  279. //break;
  280. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  281. iconName = variables["actionIconReturn"].String();
  282. break;
  283. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  284. iconName = variables["actionIconNoReturn"].String();
  285. break;
  286. }
  287. auto anim = std::make_shared<CAnimation>(iconName);
  288. w->setImage(anim, false);
  289. w->redraw();
  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.makingTurn())
  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. boost::optional<uint32_t> BattleWindow::getQueueHoveredUnitId()
  464. {
  465. return queue->getHoveredUnitIdIfAny();
  466. }
  467. void BattleWindow::showAll(SDL_Surface *to)
  468. {
  469. CIntObject::showAll(to);
  470. if (GH.screenDimensions().x != 800 || GH.screenDimensions().y !=600)
  471. CMessage::drawBorder(owner.curInt->playerID, to, pos.w+28, pos.h+29, pos.x-14, pos.y-15);
  472. }
  473. void BattleWindow::show(SDL_Surface *to)
  474. {
  475. CIntObject::show(to);
  476. LOCPLINT->cingconsole->show(to);
  477. }
  478. void BattleWindow::close()
  479. {
  480. if(GH.topInt().get() != this)
  481. logGlobal->error("Only top interface must be closed");
  482. GH.popInts(1);
  483. }