CBattleInterface.cpp 27 KB

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