BattleInterface.cpp 23 KB

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