BattleInterface.cpp 26 KB

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