BattleInterface.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. /*
  2. * BattleInterface.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 "BattleInterface.h"
  12. #include "BattleActionsController.h"
  13. #include "BattleAnimationClasses.h"
  14. #include "BattleConsole.h"
  15. #include "BattleEffectsController.h"
  16. #include "BattleFieldController.h"
  17. #include "BattleHero.h"
  18. #include "BattleObstacleController.h"
  19. #include "BattleProjectileController.h"
  20. #include "BattleRenderer.h"
  21. #include "BattleResultWindow.h"
  22. #include "BattleSiegeController.h"
  23. #include "BattleStacksController.h"
  24. #include "BattleWindow.h"
  25. #include "CreatureAnimation.h"
  26. #include "../CPlayerInterface.h"
  27. #include "../GameEngine.h"
  28. #include "../GameInstance.h"
  29. #include "../adventureMap/AdventureMapInterface.h"
  30. #include "../gui/CursorHandler.h"
  31. #include "../gui/WindowHandler.h"
  32. #include "../media/IMusicPlayer.h"
  33. #include "../media/ISoundPlayer.h"
  34. #include "../render/Canvas.h"
  35. #include "../windows/CTutorialWindow.h"
  36. #include "../../lib/BattleFieldHandler.h"
  37. #include "../../lib/CConfigHandler.h"
  38. #include "../../lib/CStack.h"
  39. #include "../../lib/CThreadHelper.h"
  40. #include "../../lib/GameLibrary.h"
  41. #include "../../lib/TerrainHandler.h"
  42. #include "../../lib/UnlockGuard.h"
  43. #include "../../lib/battle/CPlayerBattleCallback.h"
  44. #include "../../lib/callback/CCallback.h"
  45. #include "../../lib/gameState/InfoAboutArmy.h"
  46. #include "../../lib/mapObjects/CGTownInstance.h"
  47. #include "../../lib/networkPacks/PacksForClientBattle.h"
  48. #include "../../lib/texts/CGeneralTextHandler.h"
  49. BattleInterface::BattleInterface(const BattleID & battleID, const CCreatureSet *army1, const CCreatureSet *army2,
  50. const CGHeroInstance *hero1, const CGHeroInstance *hero2,
  51. std::shared_ptr<CPlayerInterface> att,
  52. std::shared_ptr<CPlayerInterface> defen,
  53. std::shared_ptr<CPlayerInterface> spectatorInt)
  54. : attackingHeroInstance(hero1)
  55. , defendingHeroInstance(hero2)
  56. , attackerInt(att)
  57. , defenderInt(defen)
  58. , curInt(att)
  59. , battleID(battleID)
  60. , battleOpeningDelayActive(true)
  61. , round(0)
  62. {
  63. if(spectatorInt)
  64. {
  65. curInt = spectatorInt;
  66. }
  67. else if(!curInt)
  68. {
  69. //May happen when we are defending during network MP game -> attacker interface is just not present
  70. curInt = defenderInt;
  71. }
  72. //hot-seat -> check tactics for both players (defender may be local human)
  73. if(attackerInt && attackerInt->cb->getBattle(getBattleID())->battleGetTacticDist())
  74. tacticianInterface = attackerInt;
  75. else if(defenderInt && defenderInt->cb->getBattle(getBattleID())->battleGetTacticDist())
  76. tacticianInterface = defenderInt;
  77. //if we found interface of player with tactics, then enter tactics mode
  78. tacticsMode = static_cast<bool>(tacticianInterface);
  79. //initializing armies
  80. this->army1 = army1;
  81. this->army2 = army2;
  82. const CGTownInstance *town = getBattle()->battleGetDefendedTown();
  83. if(town && town->fortificationsLevel().wallsHealth > 0)
  84. siegeController.reset(new BattleSiegeController(*this, town));
  85. windowObject = std::make_shared<BattleWindow>(*this);
  86. projectilesController.reset(new BattleProjectileController(*this));
  87. stacksController.reset( new BattleStacksController(*this));
  88. actionsController.reset( new BattleActionsController(*this));
  89. effectsController.reset(new BattleEffectsController(*this));
  90. obstacleController.reset(new BattleObstacleController(*this));
  91. adventureInt->onAudioPaused();
  92. ongoingAnimationsState.setBusy();
  93. ENGINE->windows().pushWindow(windowObject);
  94. windowObject->blockUI(true);
  95. windowObject->updateQueue();
  96. playIntroSoundAndUnlockInterface();
  97. }
  98. void BattleInterface::playIntroSoundAndUnlockInterface()
  99. {
  100. auto onIntroPlayed = [this]()
  101. {
  102. // Make sure that battle have not ended while intro was playing AND that a different one has not started
  103. if(GAME->interface()->battleInt.get() == this)
  104. onIntroSoundPlayed();
  105. };
  106. auto bfieldType = getBattle()->battleGetBattlefieldType();
  107. const auto & battlefieldSound = bfieldType.getInfo()->musicFilename;
  108. std::vector<soundBase::soundID> battleIntroSounds =
  109. {
  110. soundBase::battle00, soundBase::battle01,
  111. soundBase::battle02, soundBase::battle03, soundBase::battle04,
  112. soundBase::battle05, soundBase::battle06, soundBase::battle07
  113. };
  114. int battleIntroSoundChannel = -1;
  115. if (!battlefieldSound.empty())
  116. battleIntroSoundChannel = ENGINE->sound().playSound(battlefieldSound);
  117. else
  118. battleIntroSoundChannel = ENGINE->sound().playSoundFromSet(battleIntroSounds);
  119. if (battleIntroSoundChannel != -1)
  120. {
  121. ENGINE->sound().setCallback(battleIntroSoundChannel, onIntroPlayed);
  122. if (settings["gameTweaks"]["skipBattleIntroMusic"].Bool())
  123. openingEnd();
  124. }
  125. else // failed to play sound
  126. {
  127. onIntroSoundPlayed();
  128. }
  129. }
  130. bool BattleInterface::openingPlaying() const
  131. {
  132. return battleOpeningDelayActive;
  133. }
  134. void BattleInterface::onIntroSoundPlayed()
  135. {
  136. if (openingPlaying())
  137. openingEnd();
  138. auto bfieldType = getBattle()->battleGetBattlefieldType();
  139. const auto & battlefieldMusic = bfieldType.getInfo()->musicFilename;
  140. if (!battlefieldMusic.empty())
  141. ENGINE->music().playMusic(battlefieldMusic, true, true);
  142. else
  143. ENGINE->music().playMusicFromSet("battle", true, true);
  144. }
  145. void BattleInterface::openingEnd()
  146. {
  147. assert(openingPlaying());
  148. if (!openingPlaying())
  149. return;
  150. onAnimationsFinished();
  151. if(tacticsMode)
  152. tacticNextStack(nullptr);
  153. activateStack();
  154. battleOpeningDelayActive = false;
  155. CTutorialWindow::openWindowFirstTime(TutorialMode::TOUCH_BATTLE);
  156. }
  157. BattleInterface::~BattleInterface()
  158. {
  159. CPlayerInterface::battleInt = nullptr;
  160. if (adventureInt)
  161. adventureInt->onAudioResumed();
  162. awaitingEvents.clear();
  163. onAnimationsFinished();
  164. }
  165. void BattleInterface::redrawBattlefield()
  166. {
  167. fieldController->redrawBackgroundWithHexes();
  168. ENGINE->windows().totalRedraw();
  169. }
  170. void BattleInterface::stackReset(const CStack * stack)
  171. {
  172. stacksController->stackReset(stack);
  173. }
  174. void BattleInterface::stackAdded(const CStack * stack)
  175. {
  176. stacksController->stackAdded(stack, false);
  177. }
  178. void BattleInterface::stackRemoved(uint32_t stackID)
  179. {
  180. stacksController->stackRemoved(stackID);
  181. fieldController->redrawBackgroundWithHexes();
  182. windowObject->updateQueue();
  183. }
  184. void BattleInterface::stackActivated(const CStack *stack)
  185. {
  186. stacksController->stackActivated(stack);
  187. }
  188. void BattleInterface::stackMoved(const CStack *stack, const BattleHexArray & destHex, int distance, bool teleport)
  189. {
  190. if (teleport)
  191. stacksController->stackTeleported(stack, destHex, distance);
  192. else
  193. stacksController->stackMoved(stack, destHex, distance);
  194. }
  195. void BattleInterface::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  196. {
  197. stacksController->stacksAreAttacked(attackedInfos);
  198. BattleSideArray<int> killedBySide{0,0};
  199. for(const StackAttackedInfo & attackedInfo : attackedInfos)
  200. {
  201. BattleSide side = attackedInfo.defender->unitSide();
  202. killedBySide.at(side) += attackedInfo.amountKilled;
  203. }
  204. for(BattleSide side : { BattleSide::ATTACKER, BattleSide::DEFENDER })
  205. {
  206. if(killedBySide.at(side) > killedBySide.at(getBattle()->otherSide(side)))
  207. setHeroAnimation(side, EHeroAnimType::DEFEAT);
  208. else if(killedBySide.at(side) < killedBySide.at(getBattle()->otherSide(side)))
  209. setHeroAnimation(side, EHeroAnimType::VICTORY);
  210. }
  211. }
  212. void BattleInterface::stackAttacking( const StackAttackInfo & attackInfo )
  213. {
  214. stacksController->stackAttacking(attackInfo);
  215. }
  216. void BattleInterface::newRoundFirst()
  217. {
  218. waitForAnimations();
  219. }
  220. void BattleInterface::newRound()
  221. {
  222. console->addText(LIBRARY->generaltexth->allTexts[412]);
  223. round++;
  224. }
  225. void BattleInterface::giveCommand(EActionType action, const BattleHex & tile, SpellID spell)
  226. {
  227. const CStack * actor = nullptr;
  228. if(action != EActionType::HERO_SPELL && action != EActionType::RETREAT && action != EActionType::SURRENDER)
  229. {
  230. actor = stacksController->getActiveStack();
  231. }
  232. auto side = getBattle()->playerToSide(curInt->playerID);
  233. if(side == BattleSide::NONE)
  234. {
  235. logGlobal->error("Player %s is not in battle", curInt->playerID.toString());
  236. return;
  237. }
  238. BattleAction ba;
  239. ba.side = side;
  240. ba.actionType = action;
  241. ba.aimToHex(tile);
  242. ba.spell = spell;
  243. sendCommand(ba, actor);
  244. }
  245. void BattleInterface::sendCommand(BattleAction command, const CStack * actor)
  246. {
  247. command.stackNumber = actor ? actor->unitId() : ((command.side == BattleSide::ATTACKER) ? -1 : -2);
  248. if(!tacticsMode)
  249. {
  250. logGlobal->trace("Setting command for %s", (actor ? actor->nodeName() : "hero"));
  251. stacksController->setActiveStack(nullptr);
  252. curInt->cb->battleMakeUnitAction(battleID, command);
  253. }
  254. else
  255. {
  256. curInt->cb->battleMakeTacticAction(battleID, command);
  257. stacksController->setActiveStack(nullptr);
  258. //next stack will be activated when action ends
  259. }
  260. ENGINE->cursor().set(Cursor::Combat::POINTER);
  261. }
  262. const CGHeroInstance * BattleInterface::getActiveHero()
  263. {
  264. const CStack *attacker = stacksController->getActiveStack();
  265. if(!attacker)
  266. {
  267. return nullptr;
  268. }
  269. if(attacker->unitSide() == BattleSide::ATTACKER)
  270. {
  271. return attackingHeroInstance;
  272. }
  273. return defendingHeroInstance;
  274. }
  275. void BattleInterface::stackIsCatapulting(const CatapultAttack & ca)
  276. {
  277. if (siegeController)
  278. siegeController->stackIsCatapulting(ca);
  279. }
  280. void BattleInterface::gateStateChanged(const EGateState state)
  281. {
  282. if (siegeController)
  283. siegeController->gateStateChanged(state);
  284. }
  285. void BattleInterface::battleFinished(const BattleResult& br, QueryID queryID)
  286. {
  287. checkForAnimations();
  288. stacksController->setActiveStack(nullptr);
  289. ENGINE->cursor().set(Cursor::Map::POINTER);
  290. curInt->waitWhileDialog();
  291. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-skip-battle-result"].Bool())
  292. {
  293. curInt->cb->selectionMade(0, queryID);
  294. windowObject->close();
  295. return;
  296. }
  297. auto wnd = std::make_shared<BattleResultWindow>(br, *(this->curInt));
  298. wnd->resultCallback = [this, queryID](ui32 selection)
  299. {
  300. curInt->cb->selectionMade(selection, queryID);
  301. };
  302. ENGINE->windows().pushWindow(wnd);
  303. curInt->waitWhileDialog(); // Avoid freeze when AI end turn after battle. Check bug #1897
  304. CPlayerInterface::battleInt.reset();
  305. }
  306. void BattleInterface::spellCast(const BattleSpellCast * sc)
  307. {
  308. // Do not deactivate anything in tactics mode
  309. // This is battlefield setup spells
  310. if(!tacticsMode)
  311. {
  312. windowObject->blockUI(true);
  313. // Disable current active stack duing the cast
  314. // Store the current activeStack to stackToActivate
  315. stacksController->deactivateStack();
  316. }
  317. ENGINE->cursor().set(Cursor::Combat::BLOCKED);
  318. const SpellID spellID = sc->spellID;
  319. if(!spellID.hasValue())
  320. return;
  321. const CSpell * spell = spellID.toSpell();
  322. auto targetedTile = sc->tile;
  323. const AudioPath & castSoundPath = spell->getCastSound();
  324. if (!castSoundPath.empty())
  325. {
  326. auto group = spell->animationInfo.projectile.empty() ?
  327. EAnimationEvents::HIT:
  328. EAnimationEvents::BEFORE_HIT;//FIXME: recheck whether this should be on projectile spawning
  329. addToAnimationStage(group, [=]() {
  330. ENGINE->sound().playSound(castSoundPath);
  331. });
  332. }
  333. if ( sc->activeCast )
  334. {
  335. const CStack * casterStack = getBattle()->battleGetStackByID(sc->casterStack);
  336. if(casterStack != nullptr )
  337. {
  338. addToAnimationStage(EAnimationEvents::BEFORE_HIT, [this, casterStack, targetedTile, spell]()
  339. {
  340. stacksController->addNewAnim(new CastAnimation(*this, casterStack, targetedTile, getBattle()->battleGetStackByPos(targetedTile), spell));
  341. displaySpellCast(spell, casterStack->getPosition());
  342. });
  343. }
  344. else
  345. {
  346. auto hero = sc->side == BattleSide::DEFENDER ? defendingHero : attackingHero;
  347. assert(hero);
  348. addToAnimationStage(EAnimationEvents::BEFORE_HIT, [this, hero, targetedTile, spell]()
  349. {
  350. stacksController->addNewAnim(new HeroCastAnimation(*this, hero, targetedTile, getBattle()->battleGetStackByPos(targetedTile), spell));
  351. });
  352. }
  353. }
  354. addToAnimationStage(EAnimationEvents::HIT, [this, spell, targetedTile](){
  355. displaySpellHit(spell, targetedTile);
  356. });
  357. //queuing affect animation
  358. for(auto & elem : sc->affectedCres)
  359. {
  360. auto stack = getBattle()->battleGetStackByID(elem, false);
  361. assert(stack);
  362. if(stack)
  363. {
  364. addToAnimationStage(EAnimationEvents::HIT, [this, stack, spell](){
  365. displaySpellEffect(spell, stack->getPosition());
  366. });
  367. }
  368. }
  369. for(auto & elem : sc->reflectedCres)
  370. {
  371. auto stack = getBattle()->battleGetStackByID(elem, false);
  372. assert(stack);
  373. addToAnimationStage(EAnimationEvents::HIT, [this, stack](){
  374. effectsController->displayEffect(EBattleEffect::MAGIC_MIRROR, stack->getPosition());
  375. });
  376. }
  377. if (!sc->resistedCres.empty())
  378. {
  379. addToAnimationStage(EAnimationEvents::HIT, [](){
  380. ENGINE->sound().playSound(AudioPath::builtin("MAGICRES"));
  381. });
  382. }
  383. for(auto & elem : sc->resistedCres)
  384. {
  385. auto stack = getBattle()->battleGetStackByID(elem, false);
  386. assert(stack);
  387. addToAnimationStage(EAnimationEvents::HIT, [this, stack](){
  388. effectsController->displayEffect(EBattleEffect::RESISTANCE, stack->getPosition());
  389. });
  390. }
  391. //mana absorption
  392. if (sc->manaGained > 0)
  393. {
  394. Point leftHero = Point(15, 30);
  395. Point rightHero = Point(755, 30);
  396. BattleSide side = sc->side;
  397. addToAnimationStage(EAnimationEvents::AFTER_HIT, [this, side, leftHero, rightHero](){
  398. stacksController->addNewAnim(new EffectAnimation(*this, AnimationPath::builtin(side == BattleSide::DEFENDER ? "SP07_A.DEF" : "SP07_B.DEF"), leftHero));
  399. stacksController->addNewAnim(new EffectAnimation(*this, AnimationPath::builtin(side == BattleSide::DEFENDER ? "SP07_B.DEF" : "SP07_A.DEF"), rightHero));
  400. });
  401. }
  402. // animations will be executed by spell effects
  403. }
  404. void BattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  405. {
  406. if(stacksController->getActiveStack() != nullptr)
  407. fieldController->redrawBackgroundWithHexes();
  408. }
  409. void BattleInterface::setHeroAnimation(BattleSide side, EHeroAnimType phase)
  410. {
  411. if(side == BattleSide::ATTACKER)
  412. {
  413. if(attackingHero)
  414. attackingHero->setPhase(phase);
  415. }
  416. else
  417. {
  418. if(defendingHero)
  419. defendingHero->setPhase(phase);
  420. }
  421. }
  422. void BattleInterface::displayBattleLog(const std::vector<MetaString> & battleLog)
  423. {
  424. for(const auto & line : battleLog)
  425. {
  426. std::string formatted = line.toString();
  427. boost::algorithm::trim(formatted);
  428. appendBattleLog(formatted);
  429. }
  430. }
  431. void BattleInterface::displaySpellAnimationQueue(const CSpell * spell, const CSpell::TAnimationQueue & q, const BattleHex & destinationTile, bool isHit)
  432. {
  433. for(const CSpell::TAnimation & animation : q)
  434. {
  435. if(animation.pause > 0)
  436. stacksController->addNewAnim(new DummyAnimation(*this, animation.pause));
  437. if (!animation.effectName.empty())
  438. {
  439. const CStack * destStack = getBattle()->battleGetStackByPos(destinationTile, false);
  440. if (destStack)
  441. stacksController->addNewAnim(new ColorTransformAnimation(*this, destStack, animation.effectName, spell ));
  442. }
  443. if(!animation.resourceName.empty())
  444. {
  445. int flags = 0;
  446. if (isHit)
  447. flags |= EffectAnimation::FORCE_ON_TOP;
  448. if (animation.verticalPosition == VerticalPosition::BOTTOM)
  449. flags |= EffectAnimation::ALIGN_TO_BOTTOM;
  450. if (!destinationTile.isValid())
  451. flags |= EffectAnimation::SCREEN_FILL;
  452. if (!destinationTile.isValid())
  453. stacksController->addNewAnim(new EffectAnimation(*this, animation.resourceName, flags, animation.transparency));
  454. else
  455. stacksController->addNewAnim(new EffectAnimation(*this, animation.resourceName, destinationTile, flags, animation.transparency));
  456. }
  457. }
  458. }
  459. void BattleInterface::displaySpellCast(const CSpell * spell, const BattleHex & destinationTile)
  460. {
  461. if(spell)
  462. displaySpellAnimationQueue(spell, spell->animationInfo.cast, destinationTile, false);
  463. }
  464. void BattleInterface::displaySpellEffect(const CSpell * spell, const BattleHex & destinationTile)
  465. {
  466. if(spell)
  467. displaySpellAnimationQueue(spell, spell->animationInfo.affect, destinationTile, false);
  468. }
  469. void BattleInterface::displaySpellHit(const CSpell * spell, const BattleHex & destinationTile)
  470. {
  471. if(spell)
  472. displaySpellAnimationQueue(spell, spell->animationInfo.hit, destinationTile, true);
  473. }
  474. CPlayerInterface *BattleInterface::getCurrentPlayerInterface() const
  475. {
  476. return curInt.get();
  477. }
  478. void BattleInterface::trySetActivePlayer( PlayerColor player )
  479. {
  480. if ( attackerInt && attackerInt->playerID == player )
  481. curInt = attackerInt;
  482. if ( defenderInt && defenderInt->playerID == player )
  483. curInt = defenderInt;
  484. }
  485. void BattleInterface::activateStack()
  486. {
  487. stacksController->activateStack();
  488. const CStack * s = stacksController->getActiveStack();
  489. if(!s)
  490. return;
  491. windowObject->updateQueue();
  492. windowObject->blockUI(false);
  493. fieldController->redrawBackgroundWithHexes();
  494. actionsController->activateStack();
  495. ENGINE->fakeMouseMove();
  496. }
  497. bool BattleInterface::makingTurn() const
  498. {
  499. return stacksController->getActiveStack() != nullptr;
  500. }
  501. BattleID BattleInterface::getBattleID() const
  502. {
  503. return battleID;
  504. }
  505. std::shared_ptr<CPlayerBattleCallback> BattleInterface::getBattle() const
  506. {
  507. return curInt->cb->getBattle(battleID);
  508. }
  509. void BattleInterface::endAction(const BattleAction &action)
  510. {
  511. // it is possible that tactics mode ended while opening music is still playing
  512. waitForAnimations();
  513. const CStack *stack = getBattle()->battleGetStackByID(action.stackNumber);
  514. // Activate stack from stackToActivate because this might have been temporary disabled, e.g., during spell cast
  515. activateStack();
  516. stacksController->endAction(action);
  517. windowObject->updateQueue();
  518. //stack ended movement in tactics phase -> select the next one
  519. if (tacticsMode)
  520. tacticNextStack(stack);
  521. //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
  522. if(action.actionType == EActionType::HERO_SPELL)
  523. fieldController->redrawBackgroundWithHexes();
  524. }
  525. void BattleInterface::appendBattleLog(const std::string & newEntry)
  526. {
  527. console->addText(newEntry);
  528. }
  529. void BattleInterface::startAction(const BattleAction & action)
  530. {
  531. if(action.actionType == EActionType::END_TACTIC_PHASE)
  532. {
  533. windowObject->tacticPhaseEnded();
  534. return;
  535. }
  536. stacksController->startAction(action);
  537. if (!action.isUnitAction())
  538. return;
  539. assert(getBattle()->battleGetStackByID(action.stackNumber));
  540. windowObject->updateQueue();
  541. effectsController->startAction(action);
  542. }
  543. void BattleInterface::tacticPhaseEnd()
  544. {
  545. stacksController->setActiveStack(nullptr);
  546. tacticsMode = false;
  547. auto side = tacticianInterface->cb->getBattle(battleID)->playerToSide(tacticianInterface->playerID);
  548. auto action = BattleAction::makeEndOFTacticPhase(side);
  549. tacticianInterface->cb->battleMakeTacticAction(battleID, action);
  550. }
  551. static bool immobile(const CStack *s)
  552. {
  553. return s->getMovementRange() == 0; //should bound stacks be immobile?
  554. }
  555. void BattleInterface::tacticNextStack(const CStack * current)
  556. {
  557. if (!current)
  558. current = stacksController->getActiveStack();
  559. //no switching stacks when the current one is moving
  560. checkForAnimations();
  561. TStacks stacksOfMine = tacticianInterface->cb->getBattle(battleID)->battleGetStacks(CPlayerBattleCallback::ONLY_MINE);
  562. vstd::erase_if (stacksOfMine, &immobile);
  563. if (stacksOfMine.empty())
  564. {
  565. tacticPhaseEnd();
  566. return;
  567. }
  568. auto it = vstd::find(stacksOfMine, current);
  569. if (it != stacksOfMine.end() && ++it != stacksOfMine.end())
  570. stackActivated(*it);
  571. else
  572. stackActivated(stacksOfMine.front());
  573. }
  574. void BattleInterface::obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> oi)
  575. {
  576. obstacleController->obstaclePlaced(oi);
  577. }
  578. void BattleInterface::obstacleRemoved(const std::vector<ObstacleChanges> & obstacles)
  579. {
  580. obstacleController->obstacleRemoved(obstacles);
  581. }
  582. const CGHeroInstance *BattleInterface::currentHero() const
  583. {
  584. if (attackingHeroInstance && attackingHeroInstance->tempOwner == curInt->playerID)
  585. return attackingHeroInstance;
  586. if (defendingHeroInstance && defendingHeroInstance->tempOwner == curInt->playerID)
  587. return defendingHeroInstance;
  588. return nullptr;
  589. }
  590. InfoAboutHero BattleInterface::enemyHero() const
  591. {
  592. InfoAboutHero ret;
  593. if (attackingHeroInstance->tempOwner == curInt->playerID)
  594. curInt->cb->getHeroInfo(defendingHeroInstance, ret);
  595. else
  596. curInt->cb->getHeroInfo(attackingHeroInstance, ret);
  597. return ret;
  598. }
  599. void BattleInterface::requestAutofightingAIToTakeAction()
  600. {
  601. assert(curInt->isAutoFightOn);
  602. if(getBattle()->battleIsFinished())
  603. {
  604. return; // battle finished with spellcast
  605. }
  606. if (tacticsMode)
  607. {
  608. // Always end tactics mode. Player interface is blocked currently, so it's not possible that
  609. // the AI can take any action except end tactics phase (AI actions won't be triggered)
  610. //TODO implement the possibility that the AI will be triggered for further actions
  611. //TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
  612. tacticPhaseEnd();
  613. stacksController->setActiveStack(nullptr);
  614. }
  615. else
  616. {
  617. const CStack* activeStack = stacksController->getActiveStack();
  618. // If enemy is moving, activeStack can be null
  619. if (activeStack)
  620. {
  621. stacksController->setActiveStack(nullptr);
  622. // FIXME: unsafe
  623. // Run task in separate thread to avoid UI lock while AI is making turn (which might take some time)
  624. // HOWEVER this thread won't atttempt to lock game state, potentially leading to races
  625. std::thread aiThread([localBattleID = battleID, localCurInt = curInt, activeStack]()
  626. {
  627. setThreadName("autofightingAI");
  628. localCurInt->autofightingAI->activeStack(localBattleID, activeStack);
  629. });
  630. aiThread.detach();
  631. }
  632. }
  633. }
  634. void BattleInterface::castThisSpell(SpellID spellID)
  635. {
  636. actionsController->castThisSpell(spellID);
  637. }
  638. void BattleInterface::endNetwork()
  639. {
  640. ongoingAnimationsState.requestTermination();
  641. }
  642. void BattleInterface::executeStagedAnimations()
  643. {
  644. EAnimationEvents earliestStage = EAnimationEvents::COUNT;
  645. for(const auto & event : awaitingEvents)
  646. earliestStage = std::min(earliestStage, event.event);
  647. if(earliestStage != EAnimationEvents::COUNT)
  648. executeAnimationStage(earliestStage);
  649. }
  650. void BattleInterface::executeAnimationStage(EAnimationEvents event)
  651. {
  652. decltype(awaitingEvents) executingEvents;
  653. for(auto it = awaitingEvents.begin(); it != awaitingEvents.end();)
  654. {
  655. if(it->event == event)
  656. {
  657. executingEvents.push_back(*it);
  658. it = awaitingEvents.erase(it);
  659. }
  660. else
  661. ++it;
  662. }
  663. for(const auto & event : executingEvents)
  664. event.action();
  665. }
  666. void BattleInterface::onAnimationsStarted()
  667. {
  668. ongoingAnimationsState.setBusy();
  669. }
  670. void BattleInterface::onAnimationsFinished()
  671. {
  672. ongoingAnimationsState.setFree();
  673. }
  674. void BattleInterface::waitForAnimations()
  675. {
  676. {
  677. auto unlockInterface = vstd::makeUnlockGuard(ENGINE->interfaceMutex);
  678. ongoingAnimationsState.waitWhileBusy();
  679. }
  680. assert(!hasAnimations());
  681. assert(awaitingEvents.empty());
  682. if (!awaitingEvents.empty())
  683. {
  684. logGlobal->error("Wait for animations finished but we still have awaiting events!");
  685. awaitingEvents.clear();
  686. }
  687. }
  688. bool BattleInterface::hasAnimations()
  689. {
  690. return ongoingAnimationsState.isBusy();
  691. }
  692. void BattleInterface::checkForAnimations()
  693. {
  694. assert(!hasAnimations());
  695. if(hasAnimations())
  696. logGlobal->error("Unexpected animations state: expected all animations to be over, but some are still ongoing!");
  697. waitForAnimations();
  698. }
  699. void BattleInterface::addToAnimationStage(EAnimationEvents event, const AwaitingAnimationAction & action)
  700. {
  701. awaitingEvents.push_back({action, event});
  702. }
  703. void BattleInterface::setBattleQueueVisibility(bool visible)
  704. {
  705. windowObject->hideQueue();
  706. if(visible)
  707. windowObject->showQueue();
  708. }
  709. void BattleInterface::setStickyHeroWindowsVisibility(bool visible)
  710. {
  711. windowObject->hideStickyHeroWindows();
  712. if(visible)
  713. windowObject->showStickyHeroWindows();
  714. }
  715. void BattleInterface::setStickyQuickSpellWindowVisibility(bool visible)
  716. {
  717. windowObject->hideStickyQuickSpellWindow();
  718. if(visible)
  719. windowObject->showStickyQuickSpellWindow();
  720. }