BattleInterface.cpp 21 KB

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