BattleInterface.cpp 22 KB

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