BattleInterface.cpp 21 KB

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