BattleInterface.cpp 22 KB

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