BattleInterface.cpp 22 KB

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