BattleInterface.cpp 22 KB

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