BattleInterface.cpp 23 KB

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