BattleInterface.cpp 21 KB

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