BattleInterface.cpp 22 KB

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