BattleWindow.cpp 17 KB

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