BattleInterface.cpp 23 KB

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