CBattleInterface.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. /*
  2. * CBattleInterface.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 "CBattleInterface.h"
  12. #include "CBattleAnimations.h"
  13. #include "CBattleActionsController.h"
  14. #include "CBattleInterfaceClasses.h"
  15. #include "CCreatureAnimation.h"
  16. #include "CBattleProjectileController.h"
  17. #include "CBattleEffectsController.h"
  18. #include "CBattleObstacleController.h"
  19. #include "CBattleSiegeController.h"
  20. #include "CBattleFieldController.h"
  21. #include "CBattleControlPanel.h"
  22. #include "CBattleStacksController.h"
  23. #include "../CGameInfo.h"
  24. #include "../CMessage.h"
  25. #include "../CMusicHandler.h"
  26. #include "../CPlayerInterface.h"
  27. #include "../gui/CCanvas.h"
  28. #include "../gui/CCursorHandler.h"
  29. #include "../gui/CGuiHandler.h"
  30. #include "../windows/CAdvmapInterface.h"
  31. #include "../../CCallback.h"
  32. #include "../../lib/CStack.h"
  33. #include "../../lib/CConfigHandler.h"
  34. #include "../../lib/CGeneralTextHandler.h"
  35. #include "../../lib/CHeroHandler.h"
  36. #include "../../lib/CondSh.h"
  37. #include "../../lib/mapObjects/CGTownInstance.h"
  38. #include "../../lib/NetPacks.h"
  39. #include "../../lib/UnlockGuard.h"
  40. CondSh<bool> CBattleInterface::animsAreDisplayed(false);
  41. CondSh<BattleAction *> CBattleInterface::givenCommand(nullptr);
  42. CBattleInterface::CBattleInterface(const CCreatureSet *army1, const CCreatureSet *army2,
  43. const CGHeroInstance *hero1, const CGHeroInstance *hero2,
  44. const SDL_Rect & myRect,
  45. std::shared_ptr<CPlayerInterface> att, std::shared_ptr<CPlayerInterface> defen, std::shared_ptr<CPlayerInterface> spectatorInt)
  46. : attackingHeroInstance(hero1), defendingHeroInstance(hero2), animCount(0),
  47. attackerInt(att), defenderInt(defen), curInt(att),
  48. myTurn(false), moveStarted(false), moveSoundHander(-1), bresult(nullptr), battleActionsStarted(false)
  49. {
  50. OBJ_CONSTRUCTION;
  51. projectilesController.reset(new CBattleProjectileController(this));
  52. if(spectatorInt)
  53. {
  54. curInt = spectatorInt;
  55. }
  56. else if(!curInt)
  57. {
  58. //May happen when we are defending during network MP game -> attacker interface is just not present
  59. curInt = defenderInt;
  60. }
  61. animsAreDisplayed.setn(false);
  62. pos = myRect;
  63. strongInterest = true;
  64. givenCommand.setn(nullptr);
  65. //hot-seat -> check tactics for both players (defender may be local human)
  66. if(attackerInt && attackerInt->cb->battleGetTacticDist())
  67. tacticianInterface = attackerInt;
  68. else if(defenderInt && defenderInt->cb->battleGetTacticDist())
  69. tacticianInterface = defenderInt;
  70. //if we found interface of player with tactics, then enter tactics mode
  71. tacticsMode = static_cast<bool>(tacticianInterface);
  72. //create stack queue
  73. bool embedQueue;
  74. std::string queueSize = settings["battle"]["queueSize"].String();
  75. if(queueSize == "auto")
  76. embedQueue = screen->h < 700;
  77. else
  78. embedQueue = screen->h < 700 || queueSize == "small";
  79. queue = std::make_shared<CStackQueue>(embedQueue, this);
  80. if(!embedQueue)
  81. {
  82. if (settings["battle"]["showQueue"].Bool())
  83. pos.y += queue->pos.h / 2; //center whole window
  84. queue->moveTo(Point(pos.x, pos.y - queue->pos.h));
  85. }
  86. //preparing siege info
  87. const CGTownInstance *town = curInt->cb->battleGetDefendedTown();
  88. if(town && town->hasFort())
  89. siegeController.reset(new CBattleSiegeController(this, town));
  90. CPlayerInterface::battleInt = this;
  91. //initializing armies
  92. this->army1 = army1;
  93. this->army2 = army2;
  94. controlPanel = std::make_shared<CBattleControlPanel>(this, Point(0, 556));
  95. //preparing menu background and terrain
  96. fieldController.reset( new CBattleFieldController(this));
  97. stacksController.reset( new CBattleStacksController(this));
  98. actionsController.reset( new CBattleActionsController(this));
  99. effectsController.reset(new CBattleEffectsController(this));
  100. //loading hero animations
  101. if(hero1) // attacking hero
  102. {
  103. std::string battleImage;
  104. if(!hero1->type->battleImage.empty())
  105. {
  106. battleImage = hero1->type->battleImage;
  107. }
  108. else
  109. {
  110. if(hero1->sex)
  111. battleImage = hero1->type->heroClass->imageBattleFemale;
  112. else
  113. battleImage = hero1->type->heroClass->imageBattleMale;
  114. }
  115. attackingHero = std::make_shared<CBattleHero>(battleImage, false, hero1->tempOwner, hero1->tempOwner == curInt->playerID ? hero1 : nullptr, this);
  116. auto img = attackingHero->animation->getImage(0, 0, true);
  117. if(img)
  118. attackingHero->pos = genRect(img->height(), img->width(), pos.x - 43, pos.y - 19);
  119. }
  120. if(hero2) // defending hero
  121. {
  122. std::string battleImage;
  123. if(!hero2->type->battleImage.empty())
  124. {
  125. battleImage = hero2->type->battleImage;
  126. }
  127. else
  128. {
  129. if(hero2->sex)
  130. battleImage = hero2->type->heroClass->imageBattleFemale;
  131. else
  132. battleImage = hero2->type->heroClass->imageBattleMale;
  133. }
  134. defendingHero = std::make_shared<CBattleHero>(battleImage, true, hero2->tempOwner, hero2->tempOwner == curInt->playerID ? hero2 : nullptr, this);
  135. auto img = defendingHero->animation->getImage(0, 0, true);
  136. if(img)
  137. defendingHero->pos = genRect(img->height(), img->width(), pos.x + 693, pos.y - 19);
  138. }
  139. obstacleController.reset(new CBattleObstacleController(this));
  140. if(tacticsMode)
  141. tacticNextStack(nullptr);
  142. CCS->musich->stopMusic();
  143. battleIntroSoundChannel = CCS->soundh->playSoundFromSet(CCS->soundh->battleIntroSounds);
  144. auto onIntroPlayed = [&]()
  145. {
  146. if(LOCPLINT->battleInt)
  147. {
  148. CCS->musich->playMusicFromSet("battle", true, true);
  149. battleActionsStarted = true;
  150. activateStack();
  151. controlPanel->blockUI(settings["session"]["spectate"].Bool() || stacksController->getActiveStack() == nullptr);
  152. battleIntroSoundChannel = -1;
  153. }
  154. };
  155. CCS->soundh->setCallback(battleIntroSoundChannel, onIntroPlayed);
  156. addUsedEvents(RCLICK | MOVE | KEYBOARD);
  157. controlPanel->blockUI(true);
  158. queue->update();
  159. blockUI(true);
  160. }
  161. CBattleInterface::~CBattleInterface()
  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 CBattleInterface::setPrintCellBorders(bool set)
  178. {
  179. Settings cellBorders = settings.write["battle"]["cellBorders"];
  180. cellBorders->Bool() = set;
  181. fieldController->redrawBackgroundWithHexes();
  182. GH.totalRedraw();
  183. }
  184. void CBattleInterface::setPrintStackRange(bool set)
  185. {
  186. Settings stackRange = settings.write["battle"]["stackRange"];
  187. stackRange->Bool() = set;
  188. fieldController->redrawBackgroundWithHexes();
  189. GH.totalRedraw();
  190. }
  191. void CBattleInterface::setPrintMouseShadow(bool set)
  192. {
  193. Settings shadow = settings.write["battle"]["mouseShadow"];
  194. shadow->Bool() = set;
  195. }
  196. void CBattleInterface::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 CBattleInterface::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 CBattleInterface::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 CBattleInterface::mouseMoved(const SDL_MouseMotionEvent &event)
  246. {
  247. BattleHex selectedHex = fieldController->getHoveredHex();
  248. actionsController->handleHex(selectedHex, MOVE);
  249. controlPanel->mouseMoved(event);
  250. }
  251. void CBattleInterface::clickRight(tribool down, bool previousState)
  252. {
  253. if (!down)
  254. {
  255. actionsController->endCastingSpell();
  256. }
  257. }
  258. void CBattleInterface::stackReset(const CStack * stack)
  259. {
  260. stacksController->stackReset(stack);
  261. }
  262. void CBattleInterface::stackAdded(const CStack * stack)
  263. {
  264. stacksController->stackAdded(stack);
  265. }
  266. void CBattleInterface::stackRemoved(uint32_t stackID)
  267. {
  268. stacksController->stackRemoved(stackID);
  269. fieldController->redrawBackgroundWithHexes();
  270. queue->update();
  271. }
  272. void CBattleInterface::stackActivated(const CStack *stack) //TODO: check it all before game state is changed due to abilities
  273. {
  274. stacksController->stackActivated(stack);
  275. }
  276. void CBattleInterface::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  277. {
  278. stacksController->stackMoved(stack, destHex, distance);
  279. }
  280. void CBattleInterface::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 CBattleInterface::stackAttacking( const CStack *attacker, BattleHex dest, const CStack *attacked, bool shooting )
  300. {
  301. stacksController->stackAttacking(attacker, dest, attacked, shooting);
  302. }
  303. void CBattleInterface::newRoundFirst( int round )
  304. {
  305. waitForAnims();
  306. }
  307. void CBattleInterface::newRound(int number)
  308. {
  309. controlPanel->console->addText(CGI->generaltexth->allTexts[412]);
  310. }
  311. void CBattleInterface::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 CBattleInterface::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 * CBattleInterface::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 CBattleInterface::hexLclicked(int whichOne)
  363. {
  364. actionsController->handleHex(whichOne, LCLICK);
  365. }
  366. void CBattleInterface::stackIsCatapulting(const CatapultAttack & ca)
  367. {
  368. if (siegeController)
  369. siegeController->stackIsCatapulting(ca);
  370. }
  371. void CBattleInterface::gateStateChanged(const EGateState state)
  372. {
  373. if (siegeController)
  374. siegeController->gateStateChanged(state);
  375. }
  376. void CBattleInterface::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 CBattleInterface::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<CBattleResultWindow>(*bresult, *(this->curInt)));
  395. curInt->waitWhileDialog(); // Avoid freeze when AI end turn after battle. Check bug #1897
  396. CPlayerInterface::battleInt = nullptr;
  397. }
  398. void CBattleInterface::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, target, 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 CBattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  457. {
  458. if(stacksController->getActiveStack() != nullptr)
  459. fieldController->redrawBackgroundWithHexes();
  460. }
  461. void CBattleInterface::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 CBattleInterface::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 CBattleInterface::displaySpellAnimationQueue(const CSpell::TAnimationQueue & q, BattleHex destinationTile)
  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. if (!destinationTile.isValid())
  493. stacksController->addNewAnim(new CPointEffectAnimation(this, soundBase::invalid, animation.resourceName));
  494. else if (animation.verticalPosition == VerticalPosition::BOTTOM)
  495. stacksController->addNewAnim(new CPointEffectAnimation(this, soundBase::invalid, animation.resourceName, destinationTile, CPointEffectAnimation::ALIGN_TO_BOTTOM));
  496. else
  497. stacksController->addNewAnim(new CPointEffectAnimation(this, soundBase::invalid, animation.resourceName, destinationTile));
  498. }
  499. }
  500. }
  501. void CBattleInterface::displaySpellCast(SpellID spellID, BattleHex destinationTile)
  502. {
  503. const CSpell * spell = spellID.toSpell();
  504. if(spell)
  505. displaySpellAnimationQueue(spell->animationInfo.cast, destinationTile);
  506. }
  507. void CBattleInterface::displaySpellEffect(SpellID spellID, BattleHex destinationTile)
  508. {
  509. const CSpell *spell = spellID.toSpell();
  510. if(spell)
  511. displaySpellAnimationQueue(spell->animationInfo.affect, destinationTile);
  512. }
  513. void CBattleInterface::displaySpellHit(SpellID spellID, BattleHex destinationTile)
  514. {
  515. const CSpell * spell = spellID.toSpell();
  516. if(spell)
  517. displaySpellAnimationQueue(spell->animationInfo.hit, destinationTile);
  518. }
  519. void CBattleInterface::setAnimSpeed(int set)
  520. {
  521. Settings speed = settings.write["battle"]["animationSpeed"];
  522. speed->Float() = float(set) / 100;
  523. }
  524. int CBattleInterface::getAnimSpeed() const
  525. {
  526. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-battle-speed"].isNull())
  527. return static_cast<int>(vstd::round(settings["session"]["spectate-battle-speed"].Float() *100));
  528. return static_cast<int>(vstd::round(settings["battle"]["animationSpeed"].Float() *100));
  529. }
  530. CPlayerInterface *CBattleInterface::getCurrentPlayerInterface() const
  531. {
  532. return curInt.get();
  533. }
  534. void CBattleInterface::trySetActivePlayer( PlayerColor player )
  535. {
  536. if ( attackerInt && attackerInt->playerID == player )
  537. curInt = attackerInt;
  538. if ( defenderInt && defenderInt->playerID == player )
  539. curInt = defenderInt;
  540. }
  541. void CBattleInterface::activateStack()
  542. {
  543. if(!battleActionsStarted)
  544. return; //"show" function should re-call this function
  545. stacksController->activateStack();
  546. const CStack * s = stacksController->getActiveStack();
  547. if(!s)
  548. return;
  549. myTurn = true;
  550. queue->update();
  551. fieldController->redrawBackgroundWithHexes();
  552. actionsController->activateStack();
  553. GH.fakeMouseMove();
  554. }
  555. void CBattleInterface::endAction(const BattleAction* action)
  556. {
  557. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  558. if(action->actionType == EActionType::HERO_SPELL)
  559. setHeroAnimation(action->side, CCreatureAnim::HERO_HOLDING);
  560. stacksController->endAction(action);
  561. queue->update();
  562. if (tacticsMode) //stack ended movement in tactics phase -> select the next one
  563. tacticNextStack(stack);
  564. 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
  565. fieldController->redrawBackgroundWithHexes();
  566. // if (stacksController->getActiveStack() && !animsAreDisplayed.get() && pendingAnims.empty() && !active)
  567. // {
  568. // logGlobal->warn("Something wrong... interface was deactivated but there is no animation. Reactivating...");
  569. // controlPanel->blockUI(false);
  570. // }
  571. // else
  572. // {
  573. // block UI if no active stack (e.g. enemy turn);
  574. controlPanel->blockUI(stacksController->getActiveStack() == nullptr);
  575. // }
  576. }
  577. void CBattleInterface::hideQueue()
  578. {
  579. Settings showQueue = settings.write["battle"]["showQueue"];
  580. showQueue->Bool() = false;
  581. queue->deactivate();
  582. if (!queue->embedded)
  583. {
  584. moveBy(Point(0, -queue->pos.h / 2));
  585. GH.totalRedraw();
  586. }
  587. }
  588. void CBattleInterface::showQueue()
  589. {
  590. Settings showQueue = settings.write["battle"]["showQueue"];
  591. showQueue->Bool() = true;
  592. queue->activate();
  593. if (!queue->embedded)
  594. {
  595. moveBy(Point(0, +queue->pos.h / 2));
  596. GH.totalRedraw();
  597. }
  598. }
  599. void CBattleInterface::startAction(const BattleAction* action)
  600. {
  601. controlPanel->blockUI(true);
  602. if(action->actionType == EActionType::END_TACTIC_PHASE)
  603. {
  604. controlPanel->tacticPhaseEnded();
  605. return;
  606. }
  607. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  608. if (stack)
  609. {
  610. queue->update();
  611. }
  612. else
  613. {
  614. assert(action->actionType == EActionType::HERO_SPELL); //only cast spell is valid action without acting stack number
  615. }
  616. stacksController->startAction(action);
  617. redraw(); // redraw after deactivation, including proper handling of hovered hexes
  618. if(action->actionType == EActionType::HERO_SPELL) //when hero casts spell
  619. {
  620. setHeroAnimation(action->side, CCreatureAnim::HERO_CAST_SPELL);
  621. return;
  622. }
  623. if (!stack)
  624. {
  625. logGlobal->error("Something wrong with stackNumber in actionStarted. Stack number: %d", action->stackNumber);
  626. return;
  627. }
  628. effectsController->startAction(action);
  629. }
  630. void CBattleInterface::waitForAnims()
  631. {
  632. auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
  633. animsAreDisplayed.waitWhileTrue();
  634. }
  635. void CBattleInterface::tacticPhaseEnd()
  636. {
  637. stacksController->setActiveStack(nullptr);
  638. controlPanel->blockUI(true);
  639. tacticsMode = false;
  640. }
  641. static bool immobile(const CStack *s)
  642. {
  643. return !s->Speed(0, true); //should bound stacks be immobile?
  644. }
  645. void CBattleInterface::tacticNextStack(const CStack * current)
  646. {
  647. if (!current)
  648. current = stacksController->getActiveStack();
  649. //no switching stacks when the current one is moving
  650. waitForAnims();
  651. TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
  652. vstd::erase_if (stacksOfMine, &immobile);
  653. if (stacksOfMine.empty())
  654. {
  655. tacticPhaseEnd();
  656. return;
  657. }
  658. auto it = vstd::find(stacksOfMine, current);
  659. if (it != stacksOfMine.end() && ++it != stacksOfMine.end())
  660. stackActivated(*it);
  661. else
  662. stackActivated(stacksOfMine.front());
  663. }
  664. void CBattleInterface::obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> oi)
  665. {
  666. obstacleController->obstaclePlaced(oi);
  667. }
  668. const CGHeroInstance *CBattleInterface::currentHero() const
  669. {
  670. if (attackingHeroInstance->tempOwner == curInt->playerID)
  671. return attackingHeroInstance;
  672. else
  673. return defendingHeroInstance;
  674. }
  675. InfoAboutHero CBattleInterface::enemyHero() const
  676. {
  677. InfoAboutHero ret;
  678. if (attackingHeroInstance->tempOwner == curInt->playerID)
  679. curInt->cb->getHeroInfo(defendingHeroInstance, ret);
  680. else
  681. curInt->cb->getHeroInfo(attackingHeroInstance, ret);
  682. return ret;
  683. }
  684. void CBattleInterface::requestAutofightingAIToTakeAction()
  685. {
  686. assert(curInt->isAutoFightOn);
  687. boost::thread aiThread([&]()
  688. {
  689. auto ba = make_unique<BattleAction>(curInt->autofightingAI->activeStack(stacksController->getActiveStack()));
  690. if(curInt->cb->battleIsFinished())
  691. {
  692. return; // battle finished with spellcast
  693. }
  694. if (curInt->isAutoFightOn)
  695. {
  696. if (tacticsMode)
  697. {
  698. // Always end tactics mode. Player interface is blocked currently, so it's not possible that
  699. // the AI can take any action except end tactics phase (AI actions won't be triggered)
  700. //TODO implement the possibility that the AI will be triggered for further actions
  701. //TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
  702. stacksController->setActiveStack(nullptr);
  703. controlPanel->blockUI(true);
  704. tacticsMode = false;
  705. }
  706. else
  707. {
  708. givenCommand.setn(ba.release());
  709. }
  710. }
  711. else
  712. {
  713. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  714. activateStack();
  715. }
  716. });
  717. aiThread.detach();
  718. }
  719. void CBattleInterface::showAll(SDL_Surface *to)
  720. {
  721. show(to);
  722. }
  723. void CBattleInterface::show(SDL_Surface *to)
  724. {
  725. auto canvas = std::make_shared<CCanvas>(to);
  726. assert(to);
  727. SDL_Rect buf;
  728. SDL_GetClipRect(to, &buf);
  729. SDL_SetClipRect(to, &pos);
  730. ++animCount;
  731. fieldController->showBackground(canvas);
  732. showBattlefieldObjects(canvas);
  733. projectilesController->showProjectiles(canvas);
  734. if(battleActionsStarted)
  735. stacksController->updateBattleAnimations();
  736. SDL_SetClipRect(to, &buf); //restoring previous clip_rect
  737. showInterface(canvas);
  738. //activation of next stack, if any
  739. //TODO: should be moved to the very start of this method?
  740. //activateStack();
  741. }
  742. void CBattleInterface::showBattlefieldObjects(std::shared_ptr<CCanvas> canvas, const BattleHex & location )
  743. {
  744. if (siegeController)
  745. siegeController->showBattlefieldObjects(canvas, location);
  746. obstacleController->showBattlefieldObjects(canvas, location);
  747. stacksController->showBattlefieldObjects(canvas, location);
  748. effectsController->showBattlefieldObjects(canvas, location);
  749. }
  750. void CBattleInterface::showBattlefieldObjects(std::shared_ptr<CCanvas> canvas)
  751. {
  752. showBattlefieldObjects(canvas, BattleHex::HEX_BEFORE_ALL);
  753. // show heroes after "beforeAll" - e.g. topmost wall in siege
  754. if (attackingHero)
  755. attackingHero->show(canvas->getSurface());
  756. if (defendingHero)
  757. defendingHero->show(canvas->getSurface());
  758. for (int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  759. showBattlefieldObjects(canvas, BattleHex(i));
  760. showBattlefieldObjects(canvas, BattleHex::HEX_AFTER_ALL);
  761. }
  762. void CBattleInterface::showInterface(std::shared_ptr<CCanvas> canvas)
  763. {
  764. //showing in-game console
  765. LOCPLINT->cingconsole->show(canvas->getSurface());
  766. controlPanel->showAll(canvas->getSurface());
  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(canvas->getSurface());
  776. }
  777. //printing border around interface
  778. if (screen->w != 800 || screen->h !=600)
  779. {
  780. CMessage::drawBorder(curInt->playerID,canvas->getSurface(),posWithQueue.w + 28, posWithQueue.h + 28, posWithQueue.x-14, posWithQueue.y-15);
  781. }
  782. }
  783. void CBattleInterface::castThisSpell(SpellID spellID)
  784. {
  785. actionsController->castThisSpell(spellID);
  786. }