BattleInterface.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  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. {
  58. if(spectatorInt)
  59. {
  60. curInt = spectatorInt;
  61. }
  62. else if(!curInt)
  63. {
  64. //May happen when we are defending during network MP game -> attacker interface is just not present
  65. curInt = defenderInt;
  66. }
  67. //hot-seat -> check tactics for both players (defender may be local human)
  68. if(attackerInt && attackerInt->cb->getBattle(getBattleID())->battleGetTacticDist())
  69. tacticianInterface = attackerInt;
  70. else if(defenderInt && defenderInt->cb->getBattle(getBattleID())->battleGetTacticDist())
  71. tacticianInterface = defenderInt;
  72. //if we found interface of player with tactics, then enter tactics mode
  73. tacticsMode = static_cast<bool>(tacticianInterface);
  74. //initializing armies
  75. this->army1 = army1;
  76. this->army2 = army2;
  77. const CGTownInstance *town = getBattle()->battleGetDefendedTown();
  78. if(town && town->hasFort())
  79. siegeController.reset(new BattleSiegeController(*this, town));
  80. windowObject = std::make_shared<BattleWindow>(*this);
  81. projectilesController.reset(new BattleProjectileController(*this));
  82. stacksController.reset( new BattleStacksController(*this));
  83. actionsController.reset( new BattleActionsController(*this));
  84. effectsController.reset(new BattleEffectsController(*this));
  85. obstacleController.reset(new BattleObstacleController(*this));
  86. adventureInt->onAudioPaused();
  87. ongoingAnimationsState.set(true);
  88. GH.windows().pushWindow(windowObject);
  89. windowObject->blockUI(true);
  90. windowObject->updateQueue();
  91. playIntroSoundAndUnlockInterface();
  92. }
  93. void BattleInterface::playIntroSoundAndUnlockInterface()
  94. {
  95. auto onIntroPlayed = [this]()
  96. {
  97. // Make sure that battle have not ended while intro was playing AND that a different one has not started
  98. if(LOCPLINT->battleInt.get() == this)
  99. onIntroSoundPlayed();
  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. CTutorialWindow::openWindowFirstTime(TutorialMode::TOUCH_BATTLE);
  134. }
  135. BattleInterface::~BattleInterface()
  136. {
  137. CPlayerInterface::battleInt = nullptr;
  138. if (adventureInt)
  139. adventureInt->onAudioResumed();
  140. awaitingEvents.clear();
  141. onAnimationsFinished();
  142. }
  143. void BattleInterface::redrawBattlefield()
  144. {
  145. fieldController->redrawBackgroundWithHexes();
  146. GH.windows().totalRedraw();
  147. }
  148. void BattleInterface::stackReset(const CStack * stack)
  149. {
  150. stacksController->stackReset(stack);
  151. }
  152. void BattleInterface::stackAdded(const CStack * stack)
  153. {
  154. stacksController->stackAdded(stack, false);
  155. }
  156. void BattleInterface::stackRemoved(uint32_t stackID)
  157. {
  158. stacksController->stackRemoved(stackID);
  159. fieldController->redrawBackgroundWithHexes();
  160. windowObject->updateQueue();
  161. }
  162. void BattleInterface::stackActivated(const CStack *stack)
  163. {
  164. stacksController->stackActivated(stack);
  165. }
  166. void BattleInterface::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance, bool teleport)
  167. {
  168. if (teleport)
  169. stacksController->stackTeleported(stack, destHex, distance);
  170. else
  171. stacksController->stackMoved(stack, destHex, distance);
  172. }
  173. void BattleInterface::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  174. {
  175. stacksController->stacksAreAttacked(attackedInfos);
  176. std::array<int, 2> killedBySide = {0, 0};
  177. for(const StackAttackedInfo & attackedInfo : attackedInfos)
  178. {
  179. ui8 side = attackedInfo.defender->unitSide();
  180. killedBySide.at(side) += attackedInfo.amountKilled;
  181. }
  182. for(ui8 side = 0; side < 2; side++)
  183. {
  184. if(killedBySide.at(side) > killedBySide.at(1-side))
  185. setHeroAnimation(side, EHeroAnimType::DEFEAT);
  186. else if(killedBySide.at(side) < killedBySide.at(1-side))
  187. setHeroAnimation(side, EHeroAnimType::VICTORY);
  188. }
  189. }
  190. void BattleInterface::stackAttacking( const StackAttackInfo & attackInfo )
  191. {
  192. stacksController->stackAttacking(attackInfo);
  193. }
  194. void BattleInterface::newRoundFirst()
  195. {
  196. waitForAnimations();
  197. }
  198. void BattleInterface::newRound()
  199. {
  200. console->addText(CGI->generaltexth->allTexts[412]);
  201. }
  202. void BattleInterface::giveCommand(EActionType action, BattleHex tile, SpellID spell)
  203. {
  204. const CStack * actor = nullptr;
  205. if(action != EActionType::HERO_SPELL && action != EActionType::RETREAT && action != EActionType::SURRENDER)
  206. {
  207. actor = stacksController->getActiveStack();
  208. }
  209. auto side = getBattle()->playerToSide(curInt->playerID);
  210. if(!side)
  211. {
  212. logGlobal->error("Player %s is not in battle", curInt->playerID.toString());
  213. return;
  214. }
  215. BattleAction ba;
  216. ba.side = side.value();
  217. ba.actionType = action;
  218. ba.aimToHex(tile);
  219. ba.spell = spell;
  220. sendCommand(ba, actor);
  221. }
  222. void BattleInterface::sendCommand(BattleAction command, const CStack * actor)
  223. {
  224. command.stackNumber = actor ? actor->unitId() : ((command.side == BattleSide::ATTACKER) ? -1 : -2);
  225. if(!tacticsMode)
  226. {
  227. logGlobal->trace("Setting command for %s", (actor ? actor->nodeName() : "hero"));
  228. stacksController->setActiveStack(nullptr);
  229. curInt->cb->battleMakeUnitAction(battleID, command);
  230. }
  231. else
  232. {
  233. curInt->cb->battleMakeTacticAction(battleID, 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 AudioPath & 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 = getBattle()->battleGetStackByID(sc->casterStack);
  314. if(casterStack != nullptr )
  315. {
  316. addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]()
  317. {
  318. stacksController->addNewAnim(new CastAnimation(*this, casterStack, targetedTile, getBattle()->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, getBattle()->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 = getBattle()->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 = getBattle()->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(AudioPath::builtin("MAGICRES"));
  359. });
  360. }
  361. for(auto & elem : sc->resistedCres)
  362. {
  363. auto stack = getBattle()->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, AnimationPath::builtin(side ? "SP07_A.DEF" : "SP07_B.DEF"), leftHero));
  377. stacksController->addNewAnim(new EffectAnimation(*this, AnimationPath::builtin(side ? "SP07_B.DEF" : "SP07_A.DEF"), rightHero));
  378. });
  379. }
  380. // animations will be executed by spell effects
  381. }
  382. void BattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  383. {
  384. if(stacksController->getActiveStack() != nullptr)
  385. fieldController->redrawBackgroundWithHexes();
  386. }
  387. void BattleInterface::setHeroAnimation(ui8 side, EHeroAnimType phase)
  388. {
  389. if(side == BattleSide::ATTACKER)
  390. {
  391. if(attackingHero)
  392. attackingHero->setPhase(phase);
  393. }
  394. else
  395. {
  396. if(defendingHero)
  397. defendingHero->setPhase(phase);
  398. }
  399. }
  400. void BattleInterface::displayBattleLog(const std::vector<MetaString> & battleLog)
  401. {
  402. for(const auto & line : battleLog)
  403. {
  404. std::string formatted = line.toString();
  405. boost::algorithm::trim(formatted);
  406. appendBattleLog(formatted);
  407. }
  408. }
  409. void BattleInterface::displaySpellAnimationQueue(const CSpell * spell, const CSpell::TAnimationQueue & q, BattleHex destinationTile, bool isHit)
  410. {
  411. for(const CSpell::TAnimation & animation : q)
  412. {
  413. if(animation.pause > 0)
  414. stacksController->addNewAnim(new DummyAnimation(*this, animation.pause));
  415. if (!animation.effectName.empty())
  416. {
  417. const CStack * destStack = getBattle()->battleGetStackByPos(destinationTile, false);
  418. if (destStack)
  419. stacksController->addNewAnim(new ColorTransformAnimation(*this, destStack, animation.effectName, spell ));
  420. }
  421. if(!animation.resourceName.empty())
  422. {
  423. int flags = 0;
  424. if (isHit)
  425. flags |= EffectAnimation::FORCE_ON_TOP;
  426. if (animation.verticalPosition == VerticalPosition::BOTTOM)
  427. flags |= EffectAnimation::ALIGN_TO_BOTTOM;
  428. if (!destinationTile.isValid())
  429. flags |= EffectAnimation::SCREEN_FILL;
  430. if (!destinationTile.isValid())
  431. stacksController->addNewAnim(new EffectAnimation(*this, animation.resourceName, flags));
  432. else
  433. stacksController->addNewAnim(new EffectAnimation(*this, animation.resourceName, destinationTile, flags));
  434. }
  435. }
  436. }
  437. void BattleInterface::displaySpellCast(const CSpell * spell, BattleHex destinationTile)
  438. {
  439. if(spell)
  440. displaySpellAnimationQueue(spell, spell->animationInfo.cast, destinationTile, false);
  441. }
  442. void BattleInterface::displaySpellEffect(const CSpell * spell, BattleHex destinationTile)
  443. {
  444. if(spell)
  445. displaySpellAnimationQueue(spell, spell->animationInfo.affect, destinationTile, false);
  446. }
  447. void BattleInterface::displaySpellHit(const CSpell * spell, BattleHex destinationTile)
  448. {
  449. if(spell)
  450. displaySpellAnimationQueue(spell, spell->animationInfo.hit, destinationTile, true);
  451. }
  452. CPlayerInterface *BattleInterface::getCurrentPlayerInterface() const
  453. {
  454. return curInt.get();
  455. }
  456. void BattleInterface::trySetActivePlayer( PlayerColor player )
  457. {
  458. if ( attackerInt && attackerInt->playerID == player )
  459. curInt = attackerInt;
  460. if ( defenderInt && defenderInt->playerID == player )
  461. curInt = defenderInt;
  462. }
  463. void BattleInterface::activateStack()
  464. {
  465. stacksController->activateStack();
  466. const CStack * s = stacksController->getActiveStack();
  467. if(!s)
  468. return;
  469. windowObject->updateQueue();
  470. windowObject->blockUI(false);
  471. fieldController->redrawBackgroundWithHexes();
  472. actionsController->activateStack();
  473. GH.fakeMouseMove();
  474. }
  475. bool BattleInterface::makingTurn() const
  476. {
  477. return stacksController->getActiveStack() != nullptr;
  478. }
  479. BattleID BattleInterface::getBattleID() const
  480. {
  481. return battleID;
  482. }
  483. std::shared_ptr<CPlayerBattleCallback> BattleInterface::getBattle() const
  484. {
  485. return curInt->cb->getBattle(battleID);
  486. }
  487. void BattleInterface::endAction(const BattleAction &action)
  488. {
  489. // it is possible that tactics mode ended while opening music is still playing
  490. waitForAnimations();
  491. const CStack *stack = getBattle()->battleGetStackByID(action.stackNumber);
  492. // Activate stack from stackToActivate because this might have been temporary disabled, e.g., during spell cast
  493. activateStack();
  494. stacksController->endAction(action);
  495. windowObject->updateQueue();
  496. //stack ended movement in tactics phase -> select the next one
  497. if (tacticsMode)
  498. tacticNextStack(stack);
  499. //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
  500. if(action.actionType == EActionType::HERO_SPELL)
  501. fieldController->redrawBackgroundWithHexes();
  502. }
  503. void BattleInterface::appendBattleLog(const std::string & newEntry)
  504. {
  505. console->addText(newEntry);
  506. }
  507. void BattleInterface::startAction(const BattleAction & action)
  508. {
  509. if(action.actionType == EActionType::END_TACTIC_PHASE)
  510. {
  511. windowObject->tacticPhaseEnded();
  512. return;
  513. }
  514. stacksController->startAction(action);
  515. if (!action.isUnitAction())
  516. return;
  517. assert(getBattle()->battleGetStackByID(action.stackNumber));
  518. windowObject->updateQueue();
  519. effectsController->startAction(action);
  520. }
  521. void BattleInterface::tacticPhaseEnd()
  522. {
  523. stacksController->setActiveStack(nullptr);
  524. tacticsMode = false;
  525. auto side = tacticianInterface->cb->getBattle(battleID)->playerToSide(tacticianInterface->playerID);
  526. auto action = BattleAction::makeEndOFTacticPhase(*side);
  527. tacticianInterface->cb->battleMakeTacticAction(battleID, action);
  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->getBattle(battleID)->battleGetStacks(CPlayerBattleCallback::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. if(getBattle()->battleIsFinished())
  581. {
  582. return; // battle finished with spellcast
  583. }
  584. if (tacticsMode)
  585. {
  586. // Always end tactics mode. Player interface is blocked currently, so it's not possible that
  587. // the AI can take any action except end tactics phase (AI actions won't be triggered)
  588. //TODO implement the possibility that the AI will be triggered for further actions
  589. //TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
  590. tacticPhaseEnd();
  591. stacksController->setActiveStack(nullptr);
  592. }
  593. else
  594. {
  595. const CStack* activeStack = stacksController->getActiveStack();
  596. // If enemy is moving, activeStack can be null
  597. if (activeStack)
  598. {
  599. stacksController->setActiveStack(nullptr);
  600. // FIXME: unsafe
  601. // Run task in separate thread to avoid UI lock while AI is making turn (which might take some time)
  602. // HOWEVER this thread won't atttempt to lock game state, potentially leading to races
  603. boost::thread aiThread([this, activeStack]()
  604. {
  605. setThreadName("autofightingAI");
  606. curInt->autofightingAI->activeStack(battleID, activeStack);
  607. });
  608. aiThread.detach();
  609. }
  610. }
  611. }
  612. void BattleInterface::castThisSpell(SpellID spellID)
  613. {
  614. actionsController->castThisSpell(spellID);
  615. }
  616. void BattleInterface::executeStagedAnimations()
  617. {
  618. EAnimationEvents earliestStage = EAnimationEvents::COUNT;
  619. for(const auto & event : awaitingEvents)
  620. earliestStage = std::min(earliestStage, event.event);
  621. if(earliestStage != EAnimationEvents::COUNT)
  622. executeAnimationStage(earliestStage);
  623. }
  624. void BattleInterface::executeAnimationStage(EAnimationEvents event)
  625. {
  626. decltype(awaitingEvents) executingEvents;
  627. for(auto it = awaitingEvents.begin(); it != awaitingEvents.end();)
  628. {
  629. if(it->event == event)
  630. {
  631. executingEvents.push_back(*it);
  632. it = awaitingEvents.erase(it);
  633. }
  634. else
  635. ++it;
  636. }
  637. for(const auto & event : executingEvents)
  638. event.action();
  639. }
  640. void BattleInterface::onAnimationsStarted()
  641. {
  642. ongoingAnimationsState.setn(true);
  643. }
  644. void BattleInterface::onAnimationsFinished()
  645. {
  646. ongoingAnimationsState.setn(false);
  647. }
  648. void BattleInterface::waitForAnimations()
  649. {
  650. {
  651. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  652. ongoingAnimationsState.waitUntil(false);
  653. }
  654. assert(!hasAnimations());
  655. assert(awaitingEvents.empty());
  656. if (!awaitingEvents.empty())
  657. {
  658. logGlobal->error("Wait for animations finished but we still have awaiting events!");
  659. awaitingEvents.clear();
  660. }
  661. }
  662. bool BattleInterface::hasAnimations()
  663. {
  664. return ongoingAnimationsState.get();
  665. }
  666. void BattleInterface::checkForAnimations()
  667. {
  668. assert(!hasAnimations());
  669. if(hasAnimations())
  670. logGlobal->error("Unexpected animations state: expected all animations to be over, but some are still ongoing!");
  671. waitForAnimations();
  672. }
  673. void BattleInterface::addToAnimationStage(EAnimationEvents event, const AwaitingAnimationAction & action)
  674. {
  675. awaitingEvents.push_back({action, event});
  676. }
  677. void BattleInterface::setBattleQueueVisibility(bool visible)
  678. {
  679. windowObject->hideQueue();
  680. if(visible)
  681. windowObject->showQueue();
  682. }
  683. void BattleInterface::setStickyHeroWindowsVisibility(bool visible)
  684. {
  685. windowObject->hideStickyHeroWindows();
  686. if(visible)
  687. windowObject->showStickyHeroWindows();
  688. }