CBattleInterface.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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());
  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. //TODO: play AI tracks if battle was during AI turn
  169. //if (!curInt->makingTurn)
  170. //CCS->musich->playMusicFromSet(CCS->musich->aiMusics, -1);
  171. if (adventureInt && adventureInt->selection)
  172. {
  173. const auto & terrain = *(LOCPLINT->cb->getTile(adventureInt->selection->visitablePos())->terType);
  174. CCS->musich->playMusicFromSet("terrain", terrain.name, true, false);
  175. }
  176. animsAreDisplayed.setn(false);
  177. }
  178. void CBattleInterface::setPrintCellBorders(bool set)
  179. {
  180. Settings cellBorders = settings.write["battle"]["cellBorders"];
  181. cellBorders->Bool() = set;
  182. fieldController->redrawBackgroundWithHexes();
  183. GH.totalRedraw();
  184. }
  185. void CBattleInterface::setPrintStackRange(bool set)
  186. {
  187. Settings stackRange = settings.write["battle"]["stackRange"];
  188. stackRange->Bool() = set;
  189. fieldController->redrawBackgroundWithHexes();
  190. GH.totalRedraw();
  191. }
  192. void CBattleInterface::setPrintMouseShadow(bool set)
  193. {
  194. Settings shadow = settings.write["battle"]["mouseShadow"];
  195. shadow->Bool() = set;
  196. }
  197. void CBattleInterface::activate()
  198. {
  199. controlPanel->activate();
  200. if (curInt->isAutoFightOn)
  201. return;
  202. CIntObject::activate();
  203. if (attackingHero)
  204. attackingHero->activate();
  205. if (defendingHero)
  206. defendingHero->activate();
  207. fieldController->activate();
  208. if (settings["battle"]["showQueue"].Bool())
  209. queue->activate();
  210. LOCPLINT->cingconsole->activate();
  211. }
  212. void CBattleInterface::deactivate()
  213. {
  214. controlPanel->deactivate();
  215. CIntObject::deactivate();
  216. fieldController->deactivate();
  217. if (attackingHero)
  218. attackingHero->deactivate();
  219. if (defendingHero)
  220. defendingHero->deactivate();
  221. if (settings["battle"]["showQueue"].Bool())
  222. queue->deactivate();
  223. LOCPLINT->cingconsole->deactivate();
  224. }
  225. void CBattleInterface::keyPressed(const SDL_KeyboardEvent & key)
  226. {
  227. if(key.keysym.sym == SDLK_q && key.state == SDL_PRESSED)
  228. {
  229. if(settings["battle"]["showQueue"].Bool()) //hide queue
  230. hideQueue();
  231. else
  232. showQueue();
  233. }
  234. else if(key.keysym.sym == SDLK_f && key.state == SDL_PRESSED)
  235. {
  236. actionsController->enterCreatureCastingMode();
  237. }
  238. else if(key.keysym.sym == SDLK_ESCAPE)
  239. {
  240. if(!battleActionsStarted)
  241. CCS->soundh->stopSound(battleIntroSoundChannel);
  242. else
  243. actionsController->endCastingSpell();
  244. }
  245. }
  246. void CBattleInterface::mouseMoved(const SDL_MouseMotionEvent &sEvent)
  247. {
  248. BattleHex selectedHex = fieldController->getHoveredHex();
  249. actionsController->handleHex(selectedHex, MOVE);
  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, 2);
  295. else if(killedBySide.at(side) < killedBySide.at(1-side))
  296. setHeroAnimation(side, 3);
  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. if(!spell)
  403. return;
  404. const std::string & castSoundPath = spell->getCastSound();
  405. if (!castSoundPath.empty())
  406. CCS->soundh->playSound(castSoundPath);
  407. const auto casterStackID = sc->casterStack;
  408. const CStack * casterStack = nullptr;
  409. if(casterStackID >= 0)
  410. {
  411. casterStack = curInt->cb->battleGetStackByID(casterStackID);
  412. }
  413. Point srccoord = (sc->side ? Point(770, 60) : Point(30, 60)) + pos; //hero position by default
  414. {
  415. if(casterStack != nullptr)
  416. {
  417. srccoord = stacksController->getStackPositionAtHex(casterStack->getPosition(), casterStack);
  418. srccoord.x += 250;
  419. srccoord.y += 240;
  420. }
  421. }
  422. if(casterStack != nullptr && sc->activeCast)
  423. {
  424. //todo: custom cast animation for hero
  425. displaySpellCast(spellID, casterStack->getPosition());
  426. stacksController->addNewAnim(new CCastAnimation(this, casterStack, sc->tile, curInt->cb->battleGetStackByPos(sc->tile)));
  427. }
  428. waitForAnims(); //wait for cast animation
  429. //playing projectile animation
  430. if (sc->tile.isValid())
  431. {
  432. Point destcoord = stacksController->getStackPositionAtHex(sc->tile, curInt->cb->battleGetStackByPos(sc->tile)); //position attacked by projectile
  433. destcoord.x += 250; destcoord.y += 240;
  434. //animation angle
  435. double angle = atan2(static_cast<double>(destcoord.x - srccoord.x), static_cast<double>(destcoord.y - srccoord.y));
  436. bool Vflip = (angle < 0);
  437. if (Vflip)
  438. angle = -angle;
  439. std::string animToDisplay = spell->animationInfo.selectProjectile(angle);
  440. if(!animToDisplay.empty())
  441. {
  442. //TODO: calculate inside CEffectAnimation
  443. std::shared_ptr<CAnimation> tmp = std::make_shared<CAnimation>(animToDisplay);
  444. tmp->load(0, 0);
  445. auto first = tmp->getImage(0, 0);
  446. //displaying animation
  447. double diffX = (destcoord.x - srccoord.x)*(destcoord.x - srccoord.x);
  448. double diffY = (destcoord.y - srccoord.y)*(destcoord.y - srccoord.y);
  449. double distance = sqrt(diffX + diffY);
  450. int steps = static_cast<int>(distance / AnimationControls::getSpellEffectSpeed() + 1);
  451. int dx = (destcoord.x - srccoord.x - first->width())/steps;
  452. int dy = (destcoord.y - srccoord.y - first->height())/steps;
  453. stacksController->addNewAnim(new CEffectAnimation(this, animToDisplay, srccoord.x, srccoord.y, dx, dy, Vflip));
  454. }
  455. }
  456. waitForAnims(); //wait for projectile animation
  457. displaySpellHit(spellID, sc->tile);
  458. //queuing affect animation
  459. for(auto & elem : sc->affectedCres)
  460. {
  461. auto stack = curInt->cb->battleGetStackByID(elem, false);
  462. if(stack)
  463. displaySpellEffect(spellID, stack->getPosition());
  464. }
  465. //queuing additional animation
  466. for(auto & elem : sc->customEffects)
  467. {
  468. auto stack = curInt->cb->battleGetStackByID(elem.stack, false);
  469. if(stack)
  470. effectsController->displayEffect(EBattleEffect::EBattleEffect(elem.effect), stack->getPosition());
  471. }
  472. waitForAnims();
  473. //mana absorption
  474. if (sc->manaGained > 0)
  475. {
  476. Point leftHero = Point(15, 30) + pos;
  477. Point rightHero = Point(755, 30) + pos;
  478. stacksController->addNewAnim(new CEffectAnimation(this, sc->side ? "SP07_A.DEF" : "SP07_B.DEF", leftHero.x, leftHero.y, 0, 0, false));
  479. stacksController->addNewAnim(new CEffectAnimation(this, sc->side ? "SP07_B.DEF" : "SP07_A.DEF", rightHero.x, rightHero.y, 0, 0, false));
  480. }
  481. }
  482. void CBattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  483. {
  484. if(stacksController->getActiveStack() != nullptr)
  485. fieldController->redrawBackgroundWithHexes();
  486. }
  487. void CBattleInterface::setHeroAnimation(ui8 side, int phase)
  488. {
  489. if(side == BattleSide::ATTACKER)
  490. {
  491. if(attackingHero)
  492. attackingHero->setPhase(phase);
  493. }
  494. else
  495. {
  496. if(defendingHero)
  497. defendingHero->setPhase(phase);
  498. }
  499. }
  500. void CBattleInterface::displayBattleLog(const std::vector<MetaString> & battleLog)
  501. {
  502. for(const auto & line : battleLog)
  503. {
  504. std::string formatted = line.toString();
  505. boost::algorithm::trim(formatted);
  506. if(!controlPanel->console->addText(formatted))
  507. logGlobal->warn("Too long battle log line");
  508. }
  509. }
  510. void CBattleInterface::displaySpellAnimationQueue(const CSpell::TAnimationQueue & q, BattleHex destinationTile)
  511. {
  512. for(const CSpell::TAnimation & animation : q)
  513. {
  514. if(animation.pause > 0)
  515. stacksController->addNewAnim(new CDummyAnimation(this, animation.pause));
  516. else
  517. stacksController->addNewAnim(new CEffectAnimation(this, animation.resourceName, destinationTile, false, animation.verticalPosition == VerticalPosition::BOTTOM));
  518. }
  519. }
  520. void CBattleInterface::displaySpellCast(SpellID spellID, BattleHex destinationTile)
  521. {
  522. const CSpell * spell = spellID.toSpell();
  523. if(spell)
  524. displaySpellAnimationQueue(spell->animationInfo.cast, destinationTile);
  525. }
  526. void CBattleInterface::displaySpellEffect(SpellID spellID, BattleHex destinationTile)
  527. {
  528. const CSpell *spell = spellID.toSpell();
  529. if(spell)
  530. displaySpellAnimationQueue(spell->animationInfo.affect, destinationTile);
  531. }
  532. void CBattleInterface::displaySpellHit(SpellID spellID, BattleHex destinationTile)
  533. {
  534. const CSpell * spell = spellID.toSpell();
  535. if(spell)
  536. displaySpellAnimationQueue(spell->animationInfo.hit, destinationTile);
  537. }
  538. void CBattleInterface::setAnimSpeed(int set)
  539. {
  540. Settings speed = settings.write["battle"]["animationSpeed"];
  541. speed->Float() = float(set) / 100;
  542. }
  543. int CBattleInterface::getAnimSpeed() const
  544. {
  545. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-battle-speed"].isNull())
  546. return static_cast<int>(vstd::round(settings["session"]["spectate-battle-speed"].Float() *100));
  547. return static_cast<int>(vstd::round(settings["battle"]["animationSpeed"].Float() *100));
  548. }
  549. CPlayerInterface *CBattleInterface::getCurrentPlayerInterface() const
  550. {
  551. return curInt.get();
  552. }
  553. void CBattleInterface::trySetActivePlayer( PlayerColor player )
  554. {
  555. if ( attackerInt && attackerInt->playerID == player )
  556. curInt = attackerInt;
  557. if ( defenderInt && defenderInt->playerID == player )
  558. curInt = defenderInt;
  559. }
  560. void CBattleInterface::activateStack()
  561. {
  562. if(!battleActionsStarted)
  563. return; //"show" function should re-call this function
  564. stacksController->activateStack();
  565. const CStack * s = stacksController->getActiveStack();
  566. if(!s)
  567. return;
  568. myTurn = true;
  569. queue->update();
  570. fieldController->redrawBackgroundWithHexes();
  571. actionsController->activateStack();
  572. GH.fakeMouseMove();
  573. }
  574. void CBattleInterface::endAction(const BattleAction* action)
  575. {
  576. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  577. if(action->actionType == EActionType::HERO_SPELL)
  578. setHeroAnimation(action->side, 0);
  579. stacksController->endAction(action);
  580. queue->update();
  581. if (tacticsMode) //stack ended movement in tactics phase -> select the next one
  582. tacticNextStack(stack);
  583. 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
  584. fieldController->redrawBackgroundWithHexes();
  585. // if (stacksController->getActiveStack() && !animsAreDisplayed.get() && pendingAnims.empty() && !active)
  586. // {
  587. // logGlobal->warn("Something wrong... interface was deactivated but there is no animation. Reactivating...");
  588. // controlPanel->blockUI(false);
  589. // }
  590. // else
  591. // {
  592. // block UI if no active stack (e.g. enemy turn);
  593. controlPanel->blockUI(stacksController->getActiveStack() == nullptr);
  594. // }
  595. }
  596. void CBattleInterface::hideQueue()
  597. {
  598. Settings showQueue = settings.write["battle"]["showQueue"];
  599. showQueue->Bool() = false;
  600. queue->deactivate();
  601. if (!queue->embedded)
  602. {
  603. moveBy(Point(0, -queue->pos.h / 2));
  604. GH.totalRedraw();
  605. }
  606. }
  607. void CBattleInterface::showQueue()
  608. {
  609. Settings showQueue = settings.write["battle"]["showQueue"];
  610. showQueue->Bool() = true;
  611. queue->activate();
  612. if (!queue->embedded)
  613. {
  614. moveBy(Point(0, +queue->pos.h / 2));
  615. GH.totalRedraw();
  616. }
  617. }
  618. void CBattleInterface::startAction(const BattleAction* action)
  619. {
  620. controlPanel->blockUI(true);
  621. if(action->actionType == EActionType::END_TACTIC_PHASE)
  622. {
  623. controlPanel->tacticPhaseEnded();
  624. return;
  625. }
  626. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  627. if (stack)
  628. {
  629. queue->update();
  630. }
  631. else
  632. {
  633. assert(action->actionType == EActionType::HERO_SPELL); //only cast spell is valid action without acting stack number
  634. }
  635. stacksController->startAction(action);
  636. redraw(); // redraw after deactivation, including proper handling of hovered hexes
  637. if(action->actionType == EActionType::HERO_SPELL) //when hero casts spell
  638. {
  639. setHeroAnimation(action->side, 4);
  640. return;
  641. }
  642. if (!stack)
  643. {
  644. logGlobal->error("Something wrong with stackNumber in actionStarted. Stack number: %d", action->stackNumber);
  645. return;
  646. }
  647. effectsController->startAction(action);
  648. }
  649. void CBattleInterface::waitForAnims()
  650. {
  651. auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
  652. animsAreDisplayed.waitWhileTrue();
  653. }
  654. void CBattleInterface::tacticPhaseEnd()
  655. {
  656. stacksController->setActiveStack(nullptr);
  657. controlPanel->blockUI(true);
  658. tacticsMode = false;
  659. }
  660. static bool immobile(const CStack *s)
  661. {
  662. return !s->Speed(0, true); //should bound stacks be immobile?
  663. }
  664. void CBattleInterface::tacticNextStack(const CStack * current)
  665. {
  666. if (!current)
  667. current = stacksController->getActiveStack();
  668. //no switching stacks when the current one is moving
  669. waitForAnims();
  670. TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
  671. vstd::erase_if (stacksOfMine, &immobile);
  672. if (stacksOfMine.empty())
  673. {
  674. tacticPhaseEnd();
  675. return;
  676. }
  677. auto it = vstd::find(stacksOfMine, current);
  678. if (it != stacksOfMine.end() && ++it != stacksOfMine.end())
  679. stackActivated(*it);
  680. else
  681. stackActivated(stacksOfMine.front());
  682. }
  683. void CBattleInterface::obstaclePlaced(const CObstacleInstance & oi)
  684. {
  685. obstacleController->obstaclePlaced(oi);
  686. }
  687. const CGHeroInstance *CBattleInterface::currentHero() const
  688. {
  689. if (attackingHeroInstance->tempOwner == curInt->playerID)
  690. return attackingHeroInstance;
  691. else
  692. return defendingHeroInstance;
  693. }
  694. InfoAboutHero CBattleInterface::enemyHero() const
  695. {
  696. InfoAboutHero ret;
  697. if (attackingHeroInstance->tempOwner == curInt->playerID)
  698. curInt->cb->getHeroInfo(defendingHeroInstance, ret);
  699. else
  700. curInt->cb->getHeroInfo(attackingHeroInstance, ret);
  701. return ret;
  702. }
  703. void CBattleInterface::requestAutofightingAIToTakeAction()
  704. {
  705. assert(curInt->isAutoFightOn);
  706. boost::thread aiThread([&]()
  707. {
  708. auto ba = make_unique<BattleAction>(curInt->autofightingAI->activeStack(stacksController->getActiveStack()));
  709. if(curInt->cb->battleIsFinished())
  710. {
  711. return; // battle finished with spellcast
  712. }
  713. if (curInt->isAutoFightOn)
  714. {
  715. if (tacticsMode)
  716. {
  717. // Always end tactics mode. Player interface is blocked currently, so it's not possible that
  718. // the AI can take any action except end tactics phase (AI actions won't be triggered)
  719. //TODO implement the possibility that the AI will be triggered for further actions
  720. //TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
  721. stacksController->setActiveStack(nullptr);
  722. controlPanel->blockUI(true);
  723. tacticsMode = false;
  724. }
  725. else
  726. {
  727. givenCommand.setn(ba.release());
  728. }
  729. }
  730. else
  731. {
  732. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  733. activateStack();
  734. }
  735. });
  736. aiThread.detach();
  737. }
  738. void CBattleInterface::showAll(SDL_Surface *to)
  739. {
  740. show(to);
  741. }
  742. void CBattleInterface::show(SDL_Surface *to)
  743. {
  744. auto canvas = std::make_shared<CCanvas>(to);
  745. assert(to);
  746. SDL_Rect buf;
  747. SDL_GetClipRect(to, &buf);
  748. SDL_SetClipRect(to, &pos);
  749. ++animCount;
  750. if (stacksController->getActiveStack() != nullptr /*&& creAnims[stacksController->getActiveStack()->ID]->isIdle()*/) //show everything with range
  751. {
  752. // FIXME: any *real* reason to keep this separate? Speed difference can't be that big // TODO: move to showAll?
  753. fieldController->showBackgroundImageWithHexes(canvas);
  754. }
  755. else
  756. {
  757. fieldController->showBackgroundImage(canvas);
  758. obstacleController->showAbsoluteObstacles(canvas, pos.topLeft());
  759. if ( siegeController )
  760. siegeController->showAbsoluteObstacles(canvas, pos.topLeft());
  761. }
  762. fieldController->showHighlightedHexes(canvas);
  763. showBattlefieldObjects(canvas);
  764. projectilesController->showProjectiles(canvas);
  765. if(battleActionsStarted)
  766. stacksController->updateBattleAnimations();
  767. SDL_SetClipRect(to, &buf); //restoring previous clip_rect
  768. showInterface(canvas);
  769. //activation of next stack, if any
  770. //TODO: should be moved to the very start of this method?
  771. //activateStack();
  772. }
  773. void CBattleInterface::showBattlefieldObjects(std::shared_ptr<CCanvas> canvas, const BattleHex & location )
  774. {
  775. if (siegeController)
  776. siegeController->showBattlefieldObjects(canvas, location);
  777. obstacleController->showBattlefieldObjects(canvas, location);
  778. stacksController->showBattlefieldObjects(canvas, location);
  779. effectsController->showBattlefieldObjects(canvas, location);
  780. }
  781. void CBattleInterface::showBattlefieldObjects(std::shared_ptr<CCanvas> canvas)
  782. {
  783. showBattlefieldObjects(canvas, BattleHex::HEX_BEFORE_ALL);
  784. // show heroes after "beforeAll" - e.g. topmost wall in siege
  785. if (attackingHero)
  786. attackingHero->show(canvas->getSurface());
  787. if (defendingHero)
  788. defendingHero->show(canvas->getSurface());
  789. for (int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  790. showBattlefieldObjects(canvas, BattleHex(i));
  791. showBattlefieldObjects(canvas, BattleHex::HEX_AFTER_ALL);
  792. }
  793. void CBattleInterface::showInterface(std::shared_ptr<CCanvas> canvas)
  794. {
  795. //showing in-game console
  796. LOCPLINT->cingconsole->show(canvas->getSurface());
  797. controlPanel->showAll(canvas->getSurface());
  798. Rect posWithQueue = Rect(pos.x, pos.y, 800, 600);
  799. if (settings["battle"]["showQueue"].Bool())
  800. {
  801. if (!queue->embedded)
  802. {
  803. posWithQueue.y -= queue->pos.h;
  804. posWithQueue.h += queue->pos.h;
  805. }
  806. queue->showAll(canvas->getSurface());
  807. }
  808. //printing border around interface
  809. if (screen->w != 800 || screen->h !=600)
  810. {
  811. CMessage::drawBorder(curInt->playerID,canvas->getSurface(),posWithQueue.w + 28, posWithQueue.h + 28, posWithQueue.x-14, posWithQueue.y-15);
  812. }
  813. }
  814. void CBattleInterface::castThisSpell(SpellID spellID)
  815. {
  816. actionsController->castThisSpell(spellID);
  817. }