BattleInterface.cpp 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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 "BattleControlPanel.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. const SDL_Rect & myRect,
  45. std::shared_ptr<CPlayerInterface> att,
  46. std::shared_ptr<CPlayerInterface> defen,
  47. std::shared_ptr<CPlayerInterface> spectatorInt)
  48. : attackingHeroInstance(hero1)
  49. , defendingHeroInstance(hero2)
  50. , animCount(0)
  51. , attackerInt(att)
  52. , defenderInt(defen)
  53. , curInt(att)
  54. , myTurn(false)
  55. , moveSoundHander(-1)
  56. , bresult(nullptr)
  57. , battleActionsStarted(false)
  58. {
  59. OBJ_CONSTRUCTION;
  60. for ( auto & event : animationEvents)
  61. event.setn(false);
  62. if(spectatorInt)
  63. {
  64. curInt = spectatorInt;
  65. }
  66. else if(!curInt)
  67. {
  68. //May happen when we are defending during network MP game -> attacker interface is just not present
  69. curInt = defenderInt;
  70. }
  71. pos = myRect;
  72. strongInterest = true;
  73. givenCommand.setn(nullptr);
  74. //hot-seat -> check tactics for both players (defender may be local human)
  75. if(attackerInt && attackerInt->cb->battleGetTacticDist())
  76. tacticianInterface = attackerInt;
  77. else if(defenderInt && defenderInt->cb->battleGetTacticDist())
  78. tacticianInterface = defenderInt;
  79. //if we found interface of player with tactics, then enter tactics mode
  80. tacticsMode = static_cast<bool>(tacticianInterface);
  81. //create stack queue
  82. bool embedQueue;
  83. std::string queueSize = settings["battle"]["queueSize"].String();
  84. if(queueSize == "auto")
  85. embedQueue = screen->h < 700;
  86. else
  87. embedQueue = screen->h < 700 || queueSize == "small";
  88. queue = std::make_shared<StackQueue>(embedQueue, *this);
  89. if(!embedQueue)
  90. {
  91. if (settings["battle"]["showQueue"].Bool())
  92. pos.y += queue->pos.h / 2; //center whole window
  93. queue->moveTo(Point(pos.x, pos.y - queue->pos.h));
  94. }
  95. CPlayerInterface::battleInt = this;
  96. //initializing armies
  97. this->army1 = army1;
  98. this->army2 = army2;
  99. const CGTownInstance *town = curInt->cb->battleGetDefendedTown();
  100. if(town && town->hasFort())
  101. siegeController.reset(new BattleSiegeController(*this, town));
  102. controlPanel = std::make_shared<BattleControlPanel>(*this, Point(0, 556));
  103. projectilesController.reset(new BattleProjectileController(*this));
  104. fieldController.reset( new BattleFieldController(*this));
  105. stacksController.reset( new BattleStacksController(*this));
  106. actionsController.reset( new BattleActionsController(*this));
  107. effectsController.reset(new BattleEffectsController(*this));
  108. //loading hero animations
  109. if(hero1) // attacking hero
  110. {
  111. std::string battleImage;
  112. if(!hero1->type->battleImage.empty())
  113. {
  114. battleImage = hero1->type->battleImage;
  115. }
  116. else
  117. {
  118. if(hero1->sex)
  119. battleImage = hero1->type->heroClass->imageBattleFemale;
  120. else
  121. battleImage = hero1->type->heroClass->imageBattleMale;
  122. }
  123. attackingHero = std::make_shared<BattleHero>(battleImage, false, hero1->tempOwner, hero1->tempOwner == curInt->playerID ? hero1 : nullptr, *this);
  124. auto img = attackingHero->animation->getImage(0, 0, true);
  125. if(img)
  126. attackingHero->pos = genRect(img->height(), img->width(), pos.x - 43, pos.y - 19);
  127. }
  128. if(hero2) // defending hero
  129. {
  130. std::string battleImage;
  131. if(!hero2->type->battleImage.empty())
  132. {
  133. battleImage = hero2->type->battleImage;
  134. }
  135. else
  136. {
  137. if(hero2->sex)
  138. battleImage = hero2->type->heroClass->imageBattleFemale;
  139. else
  140. battleImage = hero2->type->heroClass->imageBattleMale;
  141. }
  142. defendingHero = std::make_shared<BattleHero>(battleImage, true, hero2->tempOwner, hero2->tempOwner == curInt->playerID ? hero2 : nullptr, *this);
  143. auto img = defendingHero->animation->getImage(0, 0, true);
  144. if(img)
  145. defendingHero->pos = genRect(img->height(), img->width(), pos.x + 693, pos.y - 19);
  146. }
  147. obstacleController.reset(new BattleObstacleController(*this));
  148. if(tacticsMode)
  149. tacticNextStack(nullptr);
  150. CCS->musich->stopMusic();
  151. battleIntroSoundChannel = CCS->soundh->playSoundFromSet(CCS->soundh->battleIntroSounds);
  152. auto onIntroPlayed = [&]()
  153. {
  154. if(LOCPLINT->battleInt)
  155. {
  156. CCS->musich->playMusicFromSet("battle", true, true);
  157. battleActionsStarted = true;
  158. activateStack();
  159. battleIntroSoundChannel = -1;
  160. }
  161. };
  162. CCS->soundh->setCallback(battleIntroSoundChannel, onIntroPlayed);
  163. addUsedEvents(RCLICK | MOVE | KEYBOARD);
  164. queue->update();
  165. controlPanel->blockUI(true);
  166. }
  167. BattleInterface::~BattleInterface()
  168. {
  169. CPlayerInterface::battleInt = nullptr;
  170. givenCommand.cond.notify_all(); //that two lines should make any stacksController->getActiveStack() waiting thread to finish
  171. assert(!active);
  172. if (active) //dirty fix for #485
  173. deactivate();
  174. if (adventureInt && adventureInt->selection)
  175. {
  176. //FIXME: this should be moved to adventureInt which should restore correct track based on selection/active player
  177. const auto & terrain = *(LOCPLINT->cb->getTile(adventureInt->selection->visitablePos())->terType);
  178. CCS->musich->playMusicFromSet("terrain", terrain.name, true, false);
  179. }
  180. assert(getAnimationCondition(EAnimationEvents::ACTION) == false);
  181. setAnimationCondition(EAnimationEvents::ACTION, false);
  182. }
  183. void BattleInterface::setPrintCellBorders(bool set)
  184. {
  185. Settings cellBorders = settings.write["battle"]["cellBorders"];
  186. cellBorders->Bool() = set;
  187. fieldController->redrawBackgroundWithHexes();
  188. GH.totalRedraw();
  189. }
  190. void BattleInterface::setPrintStackRange(bool set)
  191. {
  192. Settings stackRange = settings.write["battle"]["stackRange"];
  193. stackRange->Bool() = set;
  194. fieldController->redrawBackgroundWithHexes();
  195. GH.totalRedraw();
  196. }
  197. void BattleInterface::setPrintMouseShadow(bool set)
  198. {
  199. Settings shadow = settings.write["battle"]["mouseShadow"];
  200. shadow->Bool() = set;
  201. }
  202. void BattleInterface::activate()
  203. {
  204. controlPanel->activate();
  205. if (curInt->isAutoFightOn)
  206. return;
  207. CIntObject::activate();
  208. if (attackingHero)
  209. attackingHero->activate();
  210. if (defendingHero)
  211. defendingHero->activate();
  212. fieldController->activate();
  213. if (settings["battle"]["showQueue"].Bool())
  214. queue->activate();
  215. LOCPLINT->cingconsole->activate();
  216. }
  217. void BattleInterface::deactivate()
  218. {
  219. controlPanel->deactivate();
  220. CIntObject::deactivate();
  221. fieldController->deactivate();
  222. if (attackingHero)
  223. attackingHero->deactivate();
  224. if (defendingHero)
  225. defendingHero->deactivate();
  226. if (settings["battle"]["showQueue"].Bool())
  227. queue->deactivate();
  228. LOCPLINT->cingconsole->deactivate();
  229. }
  230. void BattleInterface::keyPressed(const SDL_KeyboardEvent & key)
  231. {
  232. if(key.keysym.sym == SDLK_q && key.state == SDL_PRESSED)
  233. {
  234. if(settings["battle"]["showQueue"].Bool()) //hide queue
  235. hideQueue();
  236. else
  237. showQueue();
  238. }
  239. else if(key.keysym.sym == SDLK_f && key.state == SDL_PRESSED)
  240. {
  241. actionsController->enterCreatureCastingMode();
  242. }
  243. else if(key.keysym.sym == SDLK_ESCAPE)
  244. {
  245. if(!battleActionsStarted)
  246. CCS->soundh->stopSound(battleIntroSoundChannel);
  247. else
  248. actionsController->endCastingSpell();
  249. }
  250. }
  251. void BattleInterface::mouseMoved(const SDL_MouseMotionEvent &event)
  252. {
  253. BattleHex selectedHex = fieldController->getHoveredHex();
  254. actionsController->handleHex(selectedHex, MOVE);
  255. controlPanel->mouseMoved(event);
  256. }
  257. void BattleInterface::clickRight(tribool down, bool previousState)
  258. {
  259. if (!down)
  260. {
  261. actionsController->endCastingSpell();
  262. }
  263. }
  264. void BattleInterface::stackReset(const CStack * stack)
  265. {
  266. stacksController->stackReset(stack);
  267. }
  268. void BattleInterface::stackAdded(const CStack * stack)
  269. {
  270. stacksController->stackAdded(stack);
  271. }
  272. void BattleInterface::stackRemoved(uint32_t stackID)
  273. {
  274. stacksController->stackRemoved(stackID);
  275. fieldController->redrawBackgroundWithHexes();
  276. queue->update();
  277. }
  278. void BattleInterface::stackActivated(const CStack *stack) //TODO: check it all before game state is changed due to abilities
  279. {
  280. stacksController->stackActivated(stack);
  281. }
  282. void BattleInterface::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  283. {
  284. stacksController->stackMoved(stack, destHex, distance);
  285. }
  286. void BattleInterface::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  287. {
  288. stacksController->stacksAreAttacked(attackedInfos);
  289. std::array<int, 2> killedBySide = {0, 0};
  290. int targets = 0;
  291. for(const StackAttackedInfo & attackedInfo : attackedInfos)
  292. {
  293. ++targets;
  294. ui8 side = attackedInfo.defender->side;
  295. killedBySide.at(side) += attackedInfo.amountKilled;
  296. }
  297. for(ui8 side = 0; side < 2; side++)
  298. {
  299. if(killedBySide.at(side) > killedBySide.at(1-side))
  300. setHeroAnimation(side, EHeroAnimType::DEFEAT);
  301. else if(killedBySide.at(side) < killedBySide.at(1-side))
  302. setHeroAnimation(side, EHeroAnimType::VICTORY);
  303. }
  304. }
  305. void BattleInterface::stackAttacking( const StackAttackInfo & attackInfo )
  306. {
  307. stacksController->stackAttacking(attackInfo);
  308. }
  309. void BattleInterface::newRoundFirst( int round )
  310. {
  311. waitForAnimationCondition(EAnimationEvents::ACTION, false);
  312. }
  313. void BattleInterface::newRound(int number)
  314. {
  315. controlPanel->console->addText(CGI->generaltexth->allTexts[412]);
  316. }
  317. void BattleInterface::giveCommand(EActionType action, BattleHex tile, si32 additional)
  318. {
  319. const CStack * actor = nullptr;
  320. if(action != EActionType::HERO_SPELL && action != EActionType::RETREAT && action != EActionType::SURRENDER)
  321. {
  322. actor = stacksController->getActiveStack();
  323. }
  324. auto side = curInt->cb->playerToSide(curInt->playerID);
  325. if(!side)
  326. {
  327. logGlobal->error("Player %s is not in battle", curInt->playerID.getStr());
  328. return;
  329. }
  330. auto ba = new BattleAction(); //is deleted in CPlayerInterface::stacksController->getActiveStack()()
  331. ba->side = side.get();
  332. ba->actionType = action;
  333. ba->aimToHex(tile);
  334. ba->actionSubtype = additional;
  335. sendCommand(ba, actor);
  336. }
  337. void BattleInterface::sendCommand(BattleAction *& command, const CStack * actor)
  338. {
  339. command->stackNumber = actor ? actor->unitId() : ((command->side == BattleSide::ATTACKER) ? -1 : -2);
  340. if(!tacticsMode)
  341. {
  342. logGlobal->trace("Setting command for %s", (actor ? actor->nodeName() : "hero"));
  343. myTurn = false;
  344. stacksController->setActiveStack(nullptr);
  345. givenCommand.setn(command);
  346. }
  347. else
  348. {
  349. curInt->cb->battleMakeTacticAction(command);
  350. vstd::clear_pointer(command);
  351. stacksController->setActiveStack(nullptr);
  352. //next stack will be activated when action ends
  353. }
  354. }
  355. const CGHeroInstance * BattleInterface::getActiveHero()
  356. {
  357. const CStack *attacker = stacksController->getActiveStack();
  358. if(!attacker)
  359. {
  360. return nullptr;
  361. }
  362. if(attacker->side == BattleSide::ATTACKER)
  363. {
  364. return attackingHeroInstance;
  365. }
  366. return defendingHeroInstance;
  367. }
  368. void BattleInterface::hexLclicked(int whichOne)
  369. {
  370. actionsController->handleHex(whichOne, LCLICK);
  371. }
  372. void BattleInterface::stackIsCatapulting(const CatapultAttack & ca)
  373. {
  374. if (siegeController)
  375. siegeController->stackIsCatapulting(ca);
  376. }
  377. void BattleInterface::gateStateChanged(const EGateState state)
  378. {
  379. if (siegeController)
  380. siegeController->gateStateChanged(state);
  381. }
  382. void BattleInterface::battleFinished(const BattleResult& br)
  383. {
  384. bresult = &br;
  385. waitForAnimationCondition(EAnimationEvents::ACTION, false);
  386. stacksController->setActiveStack(nullptr);
  387. displayBattleFinished();
  388. }
  389. void BattleInterface::displayBattleFinished()
  390. {
  391. CCS->curh->changeGraphic(ECursor::ADVENTURE,0);
  392. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-skip-battle-result"].Bool())
  393. {
  394. close();
  395. return;
  396. }
  397. GH.pushInt(std::make_shared<BattleResultWindow>(*bresult, *(this->curInt)));
  398. curInt->waitWhileDialog(); // Avoid freeze when AI end turn after battle. Check bug #1897
  399. CPlayerInterface::battleInt = nullptr;
  400. }
  401. void BattleInterface::spellCast(const BattleSpellCast * sc)
  402. {
  403. controlPanel->blockUI(true);
  404. const SpellID spellID = sc->spellID;
  405. const CSpell * spell = spellID.toSpell();
  406. auto targetedTile = sc->tile;
  407. assert(spell);
  408. if(!spell)
  409. return;
  410. const std::string & castSoundPath = spell->getCastSound();
  411. if (!castSoundPath.empty())
  412. {
  413. executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  414. CCS->soundh->playSound(castSoundPath);
  415. });
  416. }
  417. if ( sc->activeCast )
  418. {
  419. const CStack * casterStack = curInt->cb->battleGetStackByID(sc->casterStack);
  420. if(casterStack != nullptr )
  421. {
  422. executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]()
  423. {
  424. stacksController->addNewAnim(new CCastAnimation(*this, casterStack, targetedTile, curInt->cb->battleGetStackByPos(targetedTile), spell));
  425. displaySpellCast(spellID, casterStack->getPosition());
  426. });
  427. }
  428. else
  429. if (targetedTile.isValid() && !spell->animationInfo.projectile.empty())
  430. {
  431. // this is spell cast by hero with valid destination & valid projectile -> play animation
  432. const CStack * target = curInt->cb->battleGetStackByPos(targetedTile);
  433. Point srccoord = (sc->side ? Point(770, 60) : Point(30, 60)) + pos; //hero position
  434. Point destcoord = stacksController->getStackPositionAtHex(targetedTile, target); //position attacked by projectile
  435. destcoord += Point(250, 240); // FIXME: what are these constants?
  436. //FIXME: should be replaced with new hero cast animation type
  437. executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]()
  438. {
  439. projectilesController->createSpellProjectile( nullptr, srccoord, destcoord, spell);
  440. projectilesController->emitStackProjectile( nullptr );
  441. stacksController->addNewAnim(new CWaitingProjectileAnimation(*this, nullptr));
  442. });
  443. }
  444. }
  445. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  446. displaySpellHit(spellID, targetedTile);
  447. });
  448. //queuing affect animation
  449. for(auto & elem : sc->affectedCres)
  450. {
  451. auto stack = curInt->cb->battleGetStackByID(elem, false);
  452. assert(stack);
  453. if(stack)
  454. {
  455. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  456. displaySpellEffect(spellID, stack->getPosition());
  457. });
  458. }
  459. }
  460. //queuing additional animation (magic mirror / resistance)
  461. for(auto & elem : sc->customEffects)
  462. {
  463. auto stack = curInt->cb->battleGetStackByID(elem.stack, false);
  464. assert(stack);
  465. if(stack)
  466. {
  467. executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  468. effectsController->displayEffect(EBattleEffect::EBattleEffect(elem.effect), stack->getPosition());
  469. });
  470. }
  471. }
  472. //mana absorption
  473. if (sc->manaGained > 0)
  474. {
  475. Point leftHero = Point(15, 30) + pos;
  476. Point rightHero = Point(755, 30) + pos;
  477. bool side = sc->side;
  478. executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  479. stacksController->addNewAnim(new CPointEffectAnimation(*this, "", side ? "SP07_A.DEF" : "SP07_B.DEF", leftHero));
  480. stacksController->addNewAnim(new CPointEffectAnimation(*this, "", side ? "SP07_B.DEF" : "SP07_A.DEF", rightHero));
  481. });
  482. }
  483. }
  484. void BattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  485. {
  486. if(stacksController->getActiveStack() != nullptr)
  487. fieldController->redrawBackgroundWithHexes();
  488. }
  489. void BattleInterface::setHeroAnimation(ui8 side, int phase)
  490. {
  491. if(side == BattleSide::ATTACKER)
  492. {
  493. if(attackingHero)
  494. attackingHero->setPhase(phase);
  495. }
  496. else
  497. {
  498. if(defendingHero)
  499. defendingHero->setPhase(phase);
  500. }
  501. }
  502. void BattleInterface::displayBattleLog(const std::vector<MetaString> & battleLog)
  503. {
  504. for(const auto & line : battleLog)
  505. {
  506. std::string formatted = line.toString();
  507. boost::algorithm::trim(formatted);
  508. if(!controlPanel->console->addText(formatted))
  509. logGlobal->warn("Too long battle log line");
  510. }
  511. }
  512. void BattleInterface::displaySpellAnimationQueue(const CSpell::TAnimationQueue & q, BattleHex destinationTile, bool isHit)
  513. {
  514. for(const CSpell::TAnimation & animation : q)
  515. {
  516. if(animation.pause > 0)
  517. stacksController->addNewAnim(new CDummyAnimation(*this, animation.pause));
  518. else
  519. {
  520. int flags = 0;
  521. if (isHit)
  522. flags |= CPointEffectAnimation::FORCE_ON_TOP;
  523. if (animation.verticalPosition == VerticalPosition::BOTTOM)
  524. flags |= CPointEffectAnimation::ALIGN_TO_BOTTOM;
  525. if (!destinationTile.isValid())
  526. flags |= CPointEffectAnimation::SCREEN_FILL;
  527. if (!destinationTile.isValid())
  528. stacksController->addNewAnim(new CPointEffectAnimation(*this, "", animation.resourceName, flags));
  529. else
  530. stacksController->addNewAnim(new CPointEffectAnimation(*this, "", animation.resourceName, destinationTile, flags));
  531. }
  532. }
  533. }
  534. void BattleInterface::displaySpellCast(SpellID spellID, BattleHex destinationTile)
  535. {
  536. const CSpell * spell = spellID.toSpell();
  537. if(spell)
  538. displaySpellAnimationQueue(spell->animationInfo.cast, destinationTile, false);
  539. }
  540. void BattleInterface::displaySpellEffect(SpellID spellID, BattleHex destinationTile)
  541. {
  542. const CSpell *spell = spellID.toSpell();
  543. if(spell)
  544. displaySpellAnimationQueue(spell->animationInfo.affect, destinationTile, false);
  545. }
  546. void BattleInterface::displaySpellHit(SpellID spellID, BattleHex destinationTile)
  547. {
  548. const CSpell * spell = spellID.toSpell();
  549. if(spell)
  550. displaySpellAnimationQueue(spell->animationInfo.hit, destinationTile, true);
  551. }
  552. void BattleInterface::setAnimSpeed(int set)
  553. {
  554. Settings speed = settings.write["battle"]["animationSpeed"];
  555. speed->Float() = float(set) / 100;
  556. }
  557. int BattleInterface::getAnimSpeed() const
  558. {
  559. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-battle-speed"].isNull())
  560. return static_cast<int>(vstd::round(settings["session"]["spectate-battle-speed"].Float() *100));
  561. return static_cast<int>(vstd::round(settings["battle"]["animationSpeed"].Float() *100));
  562. }
  563. CPlayerInterface *BattleInterface::getCurrentPlayerInterface() const
  564. {
  565. return curInt.get();
  566. }
  567. void BattleInterface::trySetActivePlayer( PlayerColor player )
  568. {
  569. if ( attackerInt && attackerInt->playerID == player )
  570. curInt = attackerInt;
  571. if ( defenderInt && defenderInt->playerID == player )
  572. curInt = defenderInt;
  573. }
  574. void BattleInterface::activateStack()
  575. {
  576. if(!battleActionsStarted)
  577. return; //"show" function should re-call this function
  578. stacksController->activateStack();
  579. const CStack * s = stacksController->getActiveStack();
  580. if(!s)
  581. return;
  582. myTurn = true;
  583. queue->update();
  584. fieldController->redrawBackgroundWithHexes();
  585. actionsController->activateStack();
  586. GH.fakeMouseMove();
  587. }
  588. void BattleInterface::endAction(const BattleAction* action)
  589. {
  590. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  591. if(action->actionType == EActionType::HERO_SPELL)
  592. setHeroAnimation(action->side, EHeroAnimType::HOLDING);
  593. stacksController->endAction(action);
  594. queue->update();
  595. //stack ended movement in tactics phase -> select the next one
  596. if (tacticsMode)
  597. tacticNextStack(stack);
  598. //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
  599. if(action->actionType == EActionType::HERO_SPELL)
  600. fieldController->redrawBackgroundWithHexes();
  601. }
  602. void BattleInterface::hideQueue()
  603. {
  604. Settings showQueue = settings.write["battle"]["showQueue"];
  605. showQueue->Bool() = false;
  606. queue->deactivate();
  607. if (!queue->embedded)
  608. {
  609. moveBy(Point(0, -queue->pos.h / 2));
  610. GH.totalRedraw();
  611. }
  612. }
  613. void BattleInterface::showQueue()
  614. {
  615. Settings showQueue = settings.write["battle"]["showQueue"];
  616. showQueue->Bool() = true;
  617. queue->activate();
  618. if (!queue->embedded)
  619. {
  620. moveBy(Point(0, +queue->pos.h / 2));
  621. GH.totalRedraw();
  622. }
  623. }
  624. void BattleInterface::startAction(const BattleAction* action)
  625. {
  626. if(action->actionType == EActionType::END_TACTIC_PHASE)
  627. {
  628. controlPanel->tacticPhaseEnded();
  629. return;
  630. }
  631. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  632. if (stack)
  633. {
  634. queue->update();
  635. }
  636. else
  637. {
  638. assert(action->actionType == EActionType::HERO_SPELL); //only cast spell is valid action without acting stack number
  639. }
  640. stacksController->startAction(action);
  641. redraw(); // redraw after deactivation, including proper handling of hovered hexes
  642. if(action->actionType == EActionType::HERO_SPELL) //when hero casts spell
  643. {
  644. setHeroAnimation(action->side, EHeroAnimType::CAST_SPELL);
  645. return;
  646. }
  647. if (!stack)
  648. {
  649. logGlobal->error("Something wrong with stackNumber in actionStarted. Stack number: %d", action->stackNumber);
  650. return;
  651. }
  652. effectsController->startAction(action);
  653. }
  654. void BattleInterface::tacticPhaseEnd()
  655. {
  656. stacksController->setActiveStack(nullptr);
  657. tacticsMode = false;
  658. }
  659. static bool immobile(const CStack *s)
  660. {
  661. return !s->Speed(0, true); //should bound stacks be immobile?
  662. }
  663. void BattleInterface::tacticNextStack(const CStack * current)
  664. {
  665. if (!current)
  666. current = stacksController->getActiveStack();
  667. //no switching stacks when the current one is moving
  668. waitForAnimationCondition(EAnimationEvents::ACTION, false);
  669. TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
  670. vstd::erase_if (stacksOfMine, &immobile);
  671. if (stacksOfMine.empty())
  672. {
  673. tacticPhaseEnd();
  674. return;
  675. }
  676. auto it = vstd::find(stacksOfMine, current);
  677. if (it != stacksOfMine.end() && ++it != stacksOfMine.end())
  678. stackActivated(*it);
  679. else
  680. stackActivated(stacksOfMine.front());
  681. }
  682. void BattleInterface::obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> oi)
  683. {
  684. obstacleController->obstaclePlaced(oi);
  685. }
  686. const CGHeroInstance *BattleInterface::currentHero() const
  687. {
  688. if (attackingHeroInstance && attackingHeroInstance->tempOwner == curInt->playerID)
  689. return attackingHeroInstance;
  690. if (defendingHeroInstance && defendingHeroInstance->tempOwner == curInt->playerID)
  691. return defendingHeroInstance;
  692. return nullptr;
  693. }
  694. InfoAboutHero BattleInterface::enemyHero() const
  695. {
  696. InfoAboutHero ret;
  697. if (attackingHeroInstance->tempOwner == curInt->playerID)
  698. curInt->cb->getHeroInfo(defendingHeroInstance, ret);
  699. else
  700. curInt->cb->getHeroInfo(attackingHeroInstance, ret);
  701. return ret;
  702. }
  703. void BattleInterface::requestAutofightingAIToTakeAction()
  704. {
  705. assert(curInt->isAutoFightOn);
  706. boost::thread aiThread([&]()
  707. {
  708. auto ba = make_unique<BattleAction>(curInt->autofightingAI->activeStack(stacksController->getActiveStack()));
  709. if(curInt->cb->battleIsFinished())
  710. {
  711. return; // battle finished with spellcast
  712. }
  713. if (curInt->isAutoFightOn)
  714. {
  715. if (tacticsMode)
  716. {
  717. // Always end tactics mode. Player interface is blocked currently, so it's not possible that
  718. // the AI can take any action except end tactics phase (AI actions won't be triggered)
  719. //TODO implement the possibility that the AI will be triggered for further actions
  720. //TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
  721. stacksController->setActiveStack(nullptr);
  722. tacticsMode = false;
  723. }
  724. else
  725. {
  726. givenCommand.setn(ba.release());
  727. }
  728. }
  729. else
  730. {
  731. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  732. activateStack();
  733. }
  734. });
  735. aiThread.detach();
  736. }
  737. void BattleInterface::showAll(SDL_Surface *to)
  738. {
  739. show(to);
  740. }
  741. void BattleInterface::show(SDL_Surface *to)
  742. {
  743. Canvas canvas(to);
  744. assert(to);
  745. SDL_Rect buf;
  746. SDL_GetClipRect(to, &buf);
  747. SDL_SetClipRect(to, &pos);
  748. ++animCount;
  749. fieldController->renderBattlefield(canvas);
  750. if(battleActionsStarted)
  751. stacksController->updateBattleAnimations();
  752. SDL_SetClipRect(to, &buf); //restoring previous clip_rect
  753. showInterface(to);
  754. }
  755. void BattleInterface::collectRenderableObjects(BattleRenderer & renderer)
  756. {
  757. if (attackingHero)
  758. {
  759. renderer.insert(EBattleFieldLayer::HEROES, BattleHex(0),[this](BattleRenderer::RendererRef canvas)
  760. {
  761. attackingHero->render(canvas);
  762. });
  763. }
  764. if (defendingHero)
  765. {
  766. renderer.insert(EBattleFieldLayer::HEROES, BattleHex(GameConstants::BFIELD_WIDTH-1),[this](BattleRenderer::RendererRef canvas)
  767. {
  768. defendingHero->render(canvas);
  769. });
  770. }
  771. }
  772. void BattleInterface::showInterface(SDL_Surface * to)
  773. {
  774. //showing in-game console
  775. LOCPLINT->cingconsole->show(to);
  776. controlPanel->showAll(to);
  777. Rect posWithQueue = Rect(pos.x, pos.y, 800, 600);
  778. if (settings["battle"]["showQueue"].Bool())
  779. {
  780. if (!queue->embedded)
  781. {
  782. posWithQueue.y -= queue->pos.h;
  783. posWithQueue.h += queue->pos.h;
  784. }
  785. queue->showAll(to);
  786. }
  787. //printing border around interface
  788. if (screen->w != 800 || screen->h !=600)
  789. {
  790. CMessage::drawBorder(curInt->playerID,to,posWithQueue.w + 28, posWithQueue.h + 28, posWithQueue.x-14, posWithQueue.y-15);
  791. }
  792. }
  793. void BattleInterface::castThisSpell(SpellID spellID)
  794. {
  795. actionsController->castThisSpell(spellID);
  796. }
  797. void BattleInterface::setAnimationCondition( EAnimationEvents event, bool state)
  798. {
  799. logAnim->info("setAnimationCondition: %d -> %s", static_cast<int>(event), state ? "ON" : "OFF");
  800. size_t index = static_cast<size_t>(event);
  801. animationEvents[index].setn(state);
  802. for (auto it = awaitingEvents.begin(); it != awaitingEvents.end();)
  803. {
  804. if (it->event == event && it->eventState == state)
  805. {
  806. it->action();
  807. it = awaitingEvents.erase(it);
  808. }
  809. else
  810. ++it;
  811. }
  812. }
  813. bool BattleInterface::getAnimationCondition( EAnimationEvents event)
  814. {
  815. size_t index = static_cast<size_t>(event);
  816. return animationEvents[index].get();
  817. }
  818. void BattleInterface::waitForAnimationCondition( EAnimationEvents event, bool state)
  819. {
  820. auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
  821. size_t index = static_cast<size_t>(event);
  822. animationEvents[index].waitUntil(state);
  823. }
  824. void BattleInterface::executeOnAnimationCondition( EAnimationEvents event, bool state, const AwaitingAnimationAction & action)
  825. {
  826. awaitingEvents.push_back({action, event, state});
  827. }