BattleStacksController.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. /*
  2. * BattleStacksController.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 "BattleStacksController.h"
  12. #include "BattleSiegeController.h"
  13. #include "BattleInterfaceClasses.h"
  14. #include "BattleInterface.h"
  15. #include "BattleActionsController.h"
  16. #include "BattleAnimationClasses.h"
  17. #include "BattleFieldController.h"
  18. #include "BattleEffectsController.h"
  19. #include "BattleProjectileController.h"
  20. #include "BattleWindow.h"
  21. #include "BattleRenderer.h"
  22. #include "CreatureAnimation.h"
  23. #include "../CPlayerInterface.h"
  24. #include "../CMusicHandler.h"
  25. #include "../CGameInfo.h"
  26. #include "../gui/CGuiHandler.h"
  27. #include "../render/Colors.h"
  28. #include "../render/Canvas.h"
  29. #include "../renderSDL/SDL_Extensions.h"
  30. #include "../../CCallback.h"
  31. #include "../../lib/spells/ISpellMechanics.h"
  32. #include "../../lib/battle/BattleHex.h"
  33. #include "../../lib/CGameState.h"
  34. #include "../../lib/CStack.h"
  35. #include "../../lib/CondSh.h"
  36. #include "../../lib/TextOperations.h"
  37. static void onAnimationFinished(const CStack *stack, std::weak_ptr<CreatureAnimation> anim)
  38. {
  39. std::shared_ptr<CreatureAnimation> animation = anim.lock();
  40. if(!animation)
  41. return;
  42. if (!stack->isFrozen() && animation->getType() == ECreatureAnimType::FROZEN)
  43. animation->setType(ECreatureAnimType::HOLDING);
  44. if (animation->isIdle())
  45. {
  46. const CCreature *creature = stack->getCreature();
  47. if (stack->isFrozen())
  48. animation->setType(ECreatureAnimType::FROZEN);
  49. else
  50. if (animation->framesInGroup(ECreatureAnimType::MOUSEON) > 0)
  51. {
  52. if (CRandomGenerator::getDefault().nextDouble(99.0) < creature->animation.timeBetweenFidgets *10)
  53. animation->playOnce(ECreatureAnimType::MOUSEON);
  54. else
  55. animation->setType(ECreatureAnimType::HOLDING);
  56. }
  57. else
  58. {
  59. animation->setType(ECreatureAnimType::HOLDING);
  60. }
  61. }
  62. // always reset callback
  63. animation->onAnimationReset += std::bind(&onAnimationFinished, stack, anim);
  64. }
  65. BattleStacksController::BattleStacksController(BattleInterface & owner):
  66. owner(owner),
  67. activeStack(nullptr),
  68. stackToActivate(nullptr),
  69. selectedStack(nullptr),
  70. animIDhelper(0)
  71. {
  72. //preparing graphics for displaying amounts of creatures
  73. amountNormal = IImage::createFromFile("CMNUMWIN.BMP", EImageBlitMode::COLORKEY);
  74. amountPositive = IImage::createFromFile("CMNUMWIN.BMP", EImageBlitMode::COLORKEY);
  75. amountNegative = IImage::createFromFile("CMNUMWIN.BMP", EImageBlitMode::COLORKEY);
  76. amountEffNeutral = IImage::createFromFile("CMNUMWIN.BMP", EImageBlitMode::COLORKEY);
  77. static const auto shifterNormal = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 0.6f, 0.2f, 1.0f );
  78. static const auto shifterPositive = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 0.2f, 1.0f, 0.2f );
  79. static const auto shifterNegative = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 1.0f, 0.2f, 0.2f );
  80. static const auto shifterNeutral = ColorFilter::genRangeShifter( 0.f, 0.f, 0.f, 1.0f, 1.0f, 0.2f );
  81. amountNormal->adjustPalette(shifterNormal, 0);
  82. amountPositive->adjustPalette(shifterPositive, 0);
  83. amountNegative->adjustPalette(shifterNegative, 0);
  84. amountEffNeutral->adjustPalette(shifterNeutral, 0);
  85. //Restore border color {255, 231, 132, 255} to its original state
  86. amountNormal->resetPalette(26);
  87. amountPositive->resetPalette(26);
  88. amountNegative->resetPalette(26);
  89. amountEffNeutral->resetPalette(26);
  90. std::vector<const CStack*> stacks = owner.curInt->cb->battleGetAllStacks(true);
  91. for(const CStack * s : stacks)
  92. {
  93. stackAdded(s, true);
  94. }
  95. }
  96. BattleHex BattleStacksController::getStackCurrentPosition(const CStack * stack) const
  97. {
  98. if ( !stackAnimation.at(stack->ID)->isMoving())
  99. return stack->getPosition();
  100. if (stack->hasBonusOfType(Bonus::FLYING) && stackAnimation.at(stack->ID)->getType() == ECreatureAnimType::MOVING )
  101. return BattleHex::HEX_AFTER_ALL;
  102. for (auto & anim : currentAnimations)
  103. {
  104. // certainly ugly workaround but fixes quite annoying bug
  105. // stack position will be updated only *after* movement is finished
  106. // before this - stack is always at its initial position. Thus we need to find
  107. // its current position. Which can be found only in this class
  108. if (StackMoveAnimation *move = dynamic_cast<StackMoveAnimation*>(anim))
  109. {
  110. if (move->stack == stack)
  111. return std::max(move->prevHex, move->nextHex);
  112. }
  113. }
  114. return stack->getPosition();
  115. }
  116. void BattleStacksController::collectRenderableObjects(BattleRenderer & renderer)
  117. {
  118. auto stacks = owner.curInt->cb->battleGetAllStacks(false);
  119. for (auto stack : stacks)
  120. {
  121. if (stackAnimation.find(stack->ID) == stackAnimation.end()) //e.g. for summoned but not yet handled stacks
  122. continue;
  123. //FIXME: hack to ignore ghost stacks
  124. if ((stackAnimation[stack->ID]->getType() == ECreatureAnimType::DEAD || stackAnimation[stack->ID]->getType() == ECreatureAnimType::HOLDING) && stack->isGhost())
  125. continue;
  126. auto layer = stackAnimation[stack->ID]->isDead() ? EBattleFieldLayer::CORPSES : EBattleFieldLayer::STACKS;
  127. auto location = getStackCurrentPosition(stack);
  128. renderer.insert(layer, location, [this, stack]( BattleRenderer::RendererRef renderer ){
  129. showStack(renderer, stack);
  130. });
  131. if (stackNeedsAmountBox(stack))
  132. {
  133. renderer.insert(EBattleFieldLayer::STACK_AMOUNTS, location, [this, stack]( BattleRenderer::RendererRef renderer ){
  134. showStackAmountBox(renderer, stack);
  135. });
  136. }
  137. }
  138. }
  139. void BattleStacksController::stackReset(const CStack * stack)
  140. {
  141. owner.checkForAnimations();
  142. //reset orientation?
  143. //stackFacingRight[stack->ID] = stack->side == BattleSide::ATTACKER;
  144. auto iter = stackAnimation.find(stack->ID);
  145. if(iter == stackAnimation.end())
  146. {
  147. logGlobal->error("Unit %d have no animation", stack->ID);
  148. return;
  149. }
  150. auto animation = iter->second;
  151. if(stack->alive() && animation->isDeadOrDying())
  152. {
  153. owner.addToAnimationStage(EAnimationEvents::HIT, [=]()
  154. {
  155. addNewAnim(new ResurrectionAnimation(owner, stack));
  156. });
  157. }
  158. }
  159. void BattleStacksController::stackAdded(const CStack * stack, bool instant)
  160. {
  161. // Tower shooters have only their upper half visible
  162. static const int turretCreatureAnimationHeight = 225;
  163. stackFacingRight[stack->ID] = stack->side == BattleSide::ATTACKER; // must be set before getting stack position
  164. Point coords = getStackPositionAtHex(stack->getPosition(), stack);
  165. if(stack->initialPosition < 0) //turret
  166. {
  167. assert(owner.siegeController);
  168. const CCreature *turretCreature = owner.siegeController->getTurretCreature();
  169. stackAnimation[stack->ID] = AnimationControls::getAnimation(turretCreature);
  170. stackAnimation[stack->ID]->pos.h = turretCreatureAnimationHeight;
  171. coords = owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  172. }
  173. else
  174. {
  175. stackAnimation[stack->ID] = AnimationControls::getAnimation(stack->getCreature());
  176. stackAnimation[stack->ID]->onAnimationReset += std::bind(&onAnimationFinished, stack, stackAnimation[stack->ID]);
  177. stackAnimation[stack->ID]->pos.h = stackAnimation[stack->ID]->getHeight();
  178. }
  179. stackAnimation[stack->ID]->pos.x = coords.x;
  180. stackAnimation[stack->ID]->pos.y = coords.y;
  181. stackAnimation[stack->ID]->pos.w = stackAnimation[stack->ID]->getWidth();
  182. stackAnimation[stack->ID]->setType(ECreatureAnimType::HOLDING);
  183. if (!instant)
  184. {
  185. // immediately make stack transparent, giving correct shifter time to start
  186. auto shifterFade = ColorFilter::genAlphaShifter(0);
  187. setStackColorFilter(shifterFade, stack, nullptr, true);
  188. owner.addToAnimationStage(EAnimationEvents::HIT, [=]()
  189. {
  190. addNewAnim(new ColorTransformAnimation(owner, stack, "summonFadeIn", nullptr));
  191. if (stack->isClone())
  192. addNewAnim(new ColorTransformAnimation(owner, stack, "cloning", SpellID(SpellID::CLONE).toSpell() ));
  193. });
  194. }
  195. }
  196. void BattleStacksController::setActiveStack(const CStack *stack)
  197. {
  198. if (activeStack) // update UI
  199. stackAnimation[activeStack->ID]->setBorderColor(AnimationControls::getNoBorder());
  200. activeStack = stack;
  201. if (activeStack) // update UI
  202. stackAnimation[activeStack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  203. owner.windowObject->blockUI(activeStack == nullptr);
  204. }
  205. bool BattleStacksController::stackNeedsAmountBox(const CStack * stack) const
  206. {
  207. BattleHex currentActionTarget;
  208. if(owner.curInt->curAction)
  209. {
  210. auto target = owner.curInt->curAction->getTarget(owner.curInt->cb.get());
  211. if(!target.empty())
  212. currentActionTarget = target.at(0).hexValue;
  213. }
  214. //do not show box for singular war machines, stacked war machines with box shown are supported as extension feature
  215. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->getCount() == 1)
  216. return false;
  217. if(!stack->alive())
  218. return false;
  219. //hide box when target is going to die anyway - do not display "0 creatures"
  220. if(stack->getCount() == 0)
  221. return false;
  222. // if stack has any ongoing animation - hide the box
  223. for(auto anim : currentAnimations)
  224. {
  225. auto stackAnimation = dynamic_cast<BattleStackAnimation*>(anim);
  226. if(stackAnimation && (stackAnimation->stack->ID == stack->ID))
  227. return false;
  228. }
  229. return true;
  230. }
  231. std::shared_ptr<IImage> BattleStacksController::getStackAmountBox(const CStack * stack)
  232. {
  233. std::vector<si32> activeSpells = stack->activeSpells();
  234. if ( activeSpells.empty())
  235. return amountNormal;
  236. int effectsPositivness = 0;
  237. for ( auto const & spellID : activeSpells)
  238. effectsPositivness += CGI->spellh->objects.at(spellID)->positiveness;
  239. if (effectsPositivness > 0)
  240. return amountPositive;
  241. if (effectsPositivness < 0)
  242. return amountNegative;
  243. return amountEffNeutral;
  244. }
  245. void BattleStacksController::showStackAmountBox(Canvas & canvas, const CStack * stack)
  246. {
  247. //blitting amount background box
  248. auto amountBG = getStackAmountBox(stack);
  249. const int sideShift = stack->side == BattleSide::ATTACKER ? 1 : -1;
  250. const int reverseSideShift = stack->side == BattleSide::ATTACKER ? -1 : 1;
  251. const BattleHex nextPos = stack->getPosition() + sideShift;
  252. const bool edge = stack->getPosition() % GameConstants::BFIELD_WIDTH == (stack->side == BattleSide::ATTACKER ? GameConstants::BFIELD_WIDTH - 2 : 1);
  253. const bool moveInside = !edge && !owner.fieldController->stackCountOutsideHex(nextPos);
  254. int xAdd = (stack->side == BattleSide::ATTACKER ? 220 : 202) +
  255. (stack->doubleWide() ? 44 : 0) * sideShift +
  256. (moveInside ? amountBG->width() + 10 : 0) * reverseSideShift;
  257. int yAdd = 260 + ((stack->side == BattleSide::ATTACKER || moveInside) ? 0 : -15);
  258. canvas.draw(amountBG, stackAnimation[stack->ID]->pos.topLeft() + Point(xAdd, yAdd));
  259. //blitting amount
  260. Point textPos = stackAnimation[stack->ID]->pos.topLeft() + amountBG->dimensions()/2 + Point(xAdd, yAdd);
  261. canvas.drawText(textPos, EFonts::FONT_TINY, Colors::WHITE, ETextAlignment::CENTER, TextOperations::formatMetric(stack->getCount(), 4));
  262. }
  263. void BattleStacksController::showStack(Canvas & canvas, const CStack * stack)
  264. {
  265. ColorFilter fullFilter = ColorFilter::genEmptyShifter();
  266. for (auto const & filter : stackFilterEffects)
  267. {
  268. if (filter.target == stack)
  269. fullFilter = ColorFilter::genCombined(fullFilter, filter.effect);
  270. }
  271. stackAnimation[stack->ID]->nextFrame(canvas, fullFilter, facingRight(stack)); // do actual blit
  272. stackAnimation[stack->ID]->incrementFrame(float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000);
  273. }
  274. void BattleStacksController::update()
  275. {
  276. updateHoveredStacks();
  277. updateBattleAnimations();
  278. }
  279. void BattleStacksController::initializeBattleAnimations()
  280. {
  281. auto copiedVector = currentAnimations;
  282. for (auto & elem : copiedVector)
  283. if (elem && !elem->isInitialized())
  284. elem->tryInitialize();
  285. }
  286. void BattleStacksController::stepFrameBattleAnimations()
  287. {
  288. // operate on copy - to prevent potential iterator invalidation due to push_back's
  289. // FIXME? : remove remaining calls to addNewAnim from BattleAnimation::nextFrame (only Catapult explosion at the time of writing)
  290. auto copiedVector = currentAnimations;
  291. for (auto & elem : copiedVector)
  292. if (elem && elem->isInitialized())
  293. elem->nextFrame();
  294. }
  295. void BattleStacksController::updateBattleAnimations()
  296. {
  297. bool hadAnimations = !currentAnimations.empty();
  298. initializeBattleAnimations();
  299. stepFrameBattleAnimations();
  300. vstd::erase(currentAnimations, nullptr);
  301. if (hadAnimations && currentAnimations.empty())
  302. {
  303. owner.executeStagedAnimations();
  304. if (currentAnimations.empty())
  305. owner.onAnimationsFinished();
  306. }
  307. initializeBattleAnimations();
  308. }
  309. void BattleStacksController::addNewAnim(BattleAnimation *anim)
  310. {
  311. owner.onAnimationsStarted();
  312. currentAnimations.push_back(anim);
  313. }
  314. void BattleStacksController::stackRemoved(uint32_t stackID)
  315. {
  316. if (getActiveStack() && getActiveStack()->ID == stackID)
  317. {
  318. BattleAction *action = new BattleAction();
  319. action->side = owner.defendingHeroInstance ? (owner.curInt->playerID == owner.defendingHeroInstance->tempOwner) : false;
  320. action->actionType = EActionType::CANCEL;
  321. action->stackNumber = getActiveStack()->ID;
  322. owner.givenCommand.setn(action);
  323. setActiveStack(nullptr);
  324. }
  325. }
  326. void BattleStacksController::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  327. {
  328. owner.addToAnimationStage(EAnimationEvents::HIT, [=](){
  329. // remove any potentially erased petrification effect
  330. removeExpiredColorFilters();
  331. });
  332. for(auto & attackedInfo : attackedInfos)
  333. {
  334. if (!attackedInfo.attacker)
  335. continue;
  336. // In H3, attacked stack will not reverse on ranged attack
  337. if (attackedInfo.indirectAttack)
  338. continue;
  339. // Another type of indirect attack - dragon breath
  340. if (!CStack::isMeleeAttackPossible(attackedInfo.attacker, attackedInfo.defender))
  341. continue;
  342. // defender need to face in direction opposited to out attacker
  343. bool needsReverse = shouldAttackFacingRight(attackedInfo.attacker, attackedInfo.defender) == facingRight(attackedInfo.defender);
  344. // FIXME: this check is better, however not usable since stacksAreAttacked is called after net pack is applyed - petrification is already removed
  345. // if (needsReverse && !attackedInfo.defender->isFrozen())
  346. if (needsReverse && stackAnimation[attackedInfo.defender->ID]->getType() != ECreatureAnimType::FROZEN)
  347. {
  348. owner.addToAnimationStage(EAnimationEvents::MOVEMENT, [=]()
  349. {
  350. addNewAnim(new ReverseAnimation(owner, attackedInfo.defender, attackedInfo.defender->getPosition()));
  351. });
  352. }
  353. }
  354. for(auto & attackedInfo : attackedInfos)
  355. {
  356. bool useDeathAnim = attackedInfo.killed;
  357. bool useDefenceAnim = attackedInfo.defender->defendingAnim && !attackedInfo.indirectAttack && !attackedInfo.killed;
  358. EAnimationEvents usedEvent = useDefenceAnim ? EAnimationEvents::ATTACK : EAnimationEvents::HIT;
  359. owner.addToAnimationStage(usedEvent, [=]()
  360. {
  361. if (useDeathAnim)
  362. addNewAnim(new DeathAnimation(owner, attackedInfo.defender, attackedInfo.indirectAttack));
  363. else if(useDefenceAnim)
  364. addNewAnim(new DefenceAnimation(owner, attackedInfo.defender));
  365. else
  366. addNewAnim(new HittedAnimation(owner, attackedInfo.defender));
  367. if (attackedInfo.fireShield)
  368. owner.effectsController->displayEffect(EBattleEffect::FIRE_SHIELD, "FIRESHIE", attackedInfo.attacker->getPosition());
  369. if (attackedInfo.spellEffect != SpellID::NONE)
  370. {
  371. auto spell = attackedInfo.spellEffect.toSpell();
  372. if (!spell->getCastSound().empty())
  373. CCS->soundh->playSound(spell->getCastSound());
  374. owner.displaySpellEffect(spell, attackedInfo.defender->getPosition());
  375. }
  376. });
  377. }
  378. for (auto & attackedInfo : attackedInfos)
  379. {
  380. if (attackedInfo.rebirth)
  381. {
  382. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  383. owner.effectsController->displayEffect(EBattleEffect::RESURRECT, "RESURECT", attackedInfo.defender->getPosition());
  384. addNewAnim(new ResurrectionAnimation(owner, attackedInfo.defender));
  385. });
  386. }
  387. if (attackedInfo.killed && attackedInfo.defender->summoned)
  388. {
  389. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  390. addNewAnim(new ColorTransformAnimation(owner, attackedInfo.defender, "summonFadeOut", nullptr));
  391. stackRemoved(attackedInfo.defender->ID);
  392. });
  393. }
  394. }
  395. owner.executeStagedAnimations();
  396. owner.waitForAnimations();
  397. }
  398. void BattleStacksController::stackTeleported(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  399. {
  400. assert(destHex.size() > 0);
  401. owner.checkForAnimations();
  402. owner.addToAnimationStage(EAnimationEvents::HIT, [=](){
  403. addNewAnim( new ColorTransformAnimation(owner, stack, "teleportFadeOut", nullptr) );
  404. });
  405. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  406. stackAnimation[stack->ID]->pos.moveTo(getStackPositionAtHex(destHex.back(), stack));
  407. addNewAnim( new ColorTransformAnimation(owner, stack, "teleportFadeIn", nullptr) );
  408. });
  409. // animations will be executed by spell
  410. }
  411. void BattleStacksController::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  412. {
  413. assert(destHex.size() > 0);
  414. owner.checkForAnimations();
  415. if(shouldRotate(stack, stack->getPosition(), destHex[0]))
  416. {
  417. owner.addToAnimationStage(EAnimationEvents::ROTATE, [&]()
  418. {
  419. addNewAnim(new ReverseAnimation(owner, stack, stack->getPosition()));
  420. });
  421. }
  422. owner.addToAnimationStage(EAnimationEvents::MOVE_START, [&]()
  423. {
  424. addNewAnim(new MovementStartAnimation(owner, stack));
  425. });
  426. if (!stack->hasBonus(Selector::typeSubtype(Bonus::FLYING, 1)))
  427. {
  428. owner.addToAnimationStage(EAnimationEvents::MOVEMENT, [&]()
  429. {
  430. addNewAnim(new MovementAnimation(owner, stack, destHex, distance));
  431. });
  432. }
  433. owner.addToAnimationStage(EAnimationEvents::MOVE_END, [&]()
  434. {
  435. addNewAnim(new MovementEndAnimation(owner, stack, destHex.back()));
  436. });
  437. owner.executeStagedAnimations();
  438. owner.waitForAnimations();
  439. }
  440. bool BattleStacksController::shouldAttackFacingRight(const CStack * attacker, const CStack * defender)
  441. {
  442. bool mustReverse = owner.curInt->cb->isToReverse(
  443. attacker,
  444. defender);
  445. if (attacker->side == BattleSide::ATTACKER)
  446. return !mustReverse;
  447. else
  448. return mustReverse;
  449. }
  450. void BattleStacksController::stackAttacking( const StackAttackInfo & info )
  451. {
  452. owner.checkForAnimations();
  453. auto attacker = info.attacker;
  454. auto defender = info.defender;
  455. auto tile = info.tile;
  456. auto spellEffect = info.spellEffect;
  457. auto multiAttack = !info.secondaryDefender.empty();
  458. bool needsReverse = false;
  459. if (info.indirectAttack)
  460. {
  461. needsReverse = shouldRotate(attacker, attacker->position, info.tile);
  462. }
  463. else
  464. {
  465. needsReverse = shouldAttackFacingRight(attacker, defender) != facingRight(attacker);
  466. }
  467. if (needsReverse)
  468. {
  469. owner.addToAnimationStage(EAnimationEvents::MOVEMENT, [=]()
  470. {
  471. addNewAnim(new ReverseAnimation(owner, attacker, attacker->getPosition()));
  472. });
  473. }
  474. if(info.lucky)
  475. {
  476. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  477. owner.appendBattleLog(info.attacker->formatGeneralMessage(-45));
  478. owner.effectsController->displayEffect(EBattleEffect::GOOD_LUCK, "GOODLUCK", attacker->getPosition());
  479. });
  480. }
  481. if(info.unlucky)
  482. {
  483. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  484. owner.appendBattleLog(info.attacker->formatGeneralMessage(-44));
  485. owner.effectsController->displayEffect(EBattleEffect::BAD_LUCK, "BADLUCK", attacker->getPosition());
  486. });
  487. }
  488. if(info.deathBlow)
  489. {
  490. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  491. owner.appendBattleLog(info.attacker->formatGeneralMessage(365));
  492. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, "DEATHBLO", defender->getPosition());
  493. });
  494. for(auto elem : info.secondaryDefender)
  495. {
  496. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  497. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, elem->getPosition());
  498. });
  499. }
  500. }
  501. owner.addToAnimationStage(EAnimationEvents::ATTACK, [=]()
  502. {
  503. if (info.indirectAttack)
  504. {
  505. addNewAnim(new ShootingAnimation(owner, attacker, tile, defender));
  506. }
  507. else
  508. {
  509. addNewAnim(new MeleeAttackAnimation(owner, attacker, tile, defender, multiAttack));
  510. }
  511. });
  512. if (info.spellEffect != SpellID::NONE)
  513. {
  514. owner.addToAnimationStage(EAnimationEvents::HIT, [=]()
  515. {
  516. owner.displaySpellHit(spellEffect.toSpell(), tile);
  517. });
  518. }
  519. if (info.lifeDrain)
  520. {
  521. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=]()
  522. {
  523. owner.effectsController->displayEffect(EBattleEffect::DRAIN_LIFE, "DRAINLIF", attacker->getPosition());
  524. });
  525. }
  526. //return, animation playback will be handled by stacksAreAttacked
  527. }
  528. bool BattleStacksController::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex) const
  529. {
  530. Point begPosition = getStackPositionAtHex(oldPos,stack);
  531. Point endPosition = getStackPositionAtHex(nextHex, stack);
  532. if((begPosition.x > endPosition.x) && facingRight(stack))
  533. return true;
  534. else if((begPosition.x < endPosition.x) && !facingRight(stack))
  535. return true;
  536. return false;
  537. }
  538. void BattleStacksController::endAction(const BattleAction* action)
  539. {
  540. owner.checkForAnimations();
  541. //check if we should reverse stacks
  542. TStacks stacks = owner.curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
  543. for (const CStack *s : stacks)
  544. {
  545. bool shouldFaceRight = s && s->side == BattleSide::ATTACKER;
  546. if (s && facingRight(s) != shouldFaceRight && s->alive() && stackAnimation[s->ID]->isIdle())
  547. {
  548. addNewAnim(new ReverseAnimation(owner, s, s->getPosition()));
  549. }
  550. }
  551. owner.executeStagedAnimations();
  552. owner.waitForAnimations();
  553. owner.windowObject->blockUI(activeStack == nullptr);
  554. removeExpiredColorFilters();
  555. }
  556. void BattleStacksController::startAction(const BattleAction* action)
  557. {
  558. removeExpiredColorFilters();
  559. }
  560. void BattleStacksController::stackActivated(const CStack *stack)
  561. {
  562. stackToActivate = stack;
  563. owner.waitForAnimations();
  564. logAnim->debug("Activating next stack");
  565. owner.activateStack();
  566. }
  567. void BattleStacksController::deactivateStack()
  568. {
  569. if (!activeStack) {
  570. return;
  571. }
  572. stackToActivate = activeStack;
  573. setActiveStack(nullptr);
  574. }
  575. void BattleStacksController::activateStack()
  576. {
  577. if ( !currentAnimations.empty())
  578. return;
  579. if ( !stackToActivate)
  580. return;
  581. owner.trySetActivePlayer(stackToActivate->owner);
  582. setActiveStack(stackToActivate);
  583. stackToActivate = nullptr;
  584. const CStack * s = getActiveStack();
  585. if(!s)
  586. return;
  587. }
  588. void BattleStacksController::setSelectedStack(const CStack *stack)
  589. {
  590. selectedStack = stack;
  591. }
  592. const CStack* BattleStacksController::getSelectedStack() const
  593. {
  594. return selectedStack;
  595. }
  596. const CStack* BattleStacksController::getActiveStack() const
  597. {
  598. return activeStack;
  599. }
  600. bool BattleStacksController::facingRight(const CStack * stack) const
  601. {
  602. return stackFacingRight.at(stack->ID);
  603. }
  604. Point BattleStacksController::getStackPositionAtHex(BattleHex hexNum, const CStack * stack) const
  605. {
  606. Point ret(-500, -500); //returned value
  607. if(stack && stack->initialPosition < 0) //creatures in turrets
  608. return owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  609. static const Point basePos(-190, -139); // position of creature in topleft corner
  610. static const int imageShiftX = 30; // X offset to base pos for facing right stacks, negative for facing left
  611. ret.x = basePos.x + 22 * ( (hexNum.getY() + 1)%2 ) + 44 * hexNum.getX();
  612. ret.y = basePos.y + 42 * hexNum.getY();
  613. if (stack)
  614. {
  615. if(facingRight(stack))
  616. ret.x += imageShiftX;
  617. else
  618. ret.x -= imageShiftX;
  619. //shifting position for double - hex creatures
  620. if(stack->doubleWide())
  621. {
  622. if(stack->side == BattleSide::ATTACKER)
  623. {
  624. if(facingRight(stack))
  625. ret.x -= 44;
  626. }
  627. else
  628. {
  629. if(!facingRight(stack))
  630. ret.x += 44;
  631. }
  632. }
  633. }
  634. //returning
  635. return ret;
  636. }
  637. void BattleStacksController::setStackColorFilter(const ColorFilter & effect, const CStack * target, const CSpell * source, bool persistent)
  638. {
  639. for (auto & filter : stackFilterEffects)
  640. {
  641. if (filter.target == target && filter.source == source)
  642. {
  643. filter.effect = effect;
  644. filter.persistent = persistent;
  645. return;
  646. }
  647. }
  648. stackFilterEffects.push_back({ effect, target, source, persistent });
  649. }
  650. void BattleStacksController::removeExpiredColorFilters()
  651. {
  652. vstd::erase_if(stackFilterEffects, [&](const BattleStackFilterEffect & filter)
  653. {
  654. if (!filter.persistent)
  655. {
  656. if (filter.source && !filter.target->hasBonus(Selector::source(Bonus::SPELL_EFFECT, filter.source->id), Selector::all))
  657. return true;
  658. if (filter.effect == ColorFilter::genEmptyShifter())
  659. return true;
  660. }
  661. return false;
  662. });
  663. }
  664. void BattleStacksController::updateHoveredStacks()
  665. {
  666. auto newStacks = selectHoveredStacks();
  667. for (auto const * stack : mouseHoveredStacks)
  668. {
  669. if (vstd::contains(newStacks, stack))
  670. continue;
  671. if (stack == activeStack)
  672. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  673. else
  674. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getNoBorder());
  675. }
  676. for (auto const * stack : newStacks)
  677. {
  678. if (vstd::contains(mouseHoveredStacks, stack))
  679. continue;
  680. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getBlueBorder());
  681. if (stackAnimation[stack->ID]->framesInGroup(ECreatureAnimType::MOUSEON) > 0 && stack->alive() && !stack->isFrozen())
  682. stackAnimation[stack->ID]->playOnce(ECreatureAnimType::MOUSEON);
  683. }
  684. mouseHoveredStacks = newStacks;
  685. }
  686. std::vector<const CStack *> BattleStacksController::selectHoveredStacks()
  687. {
  688. // only allow during our turn - do not try to highlight creatures while they are in the middle of actions
  689. if (!activeStack)
  690. return {};
  691. if(owner.hasAnimations())
  692. return {};
  693. auto hoveredQueueUnitId = owner.windowObject->getQueueHoveredUnitId();
  694. if(hoveredQueueUnitId.is_initialized())
  695. {
  696. return { owner.curInt->cb->battleGetStackByID(hoveredQueueUnitId.value(), true) };
  697. }
  698. auto hoveredHex = owner.fieldController->getHoveredHex();
  699. if (!hoveredHex.isValid())
  700. return {};
  701. const spells::Caster *caster = nullptr;
  702. const CSpell *spell = nullptr;
  703. spells::Mode mode = owner.actionsController->getCurrentCastMode();
  704. spell = owner.actionsController->getCurrentSpell(hoveredHex);
  705. caster = owner.actionsController->getCurrentSpellcaster();
  706. if(caster && spell && owner.actionsController->currentActionSpellcasting(hoveredHex) ) //when casting spell
  707. {
  708. spells::Target target;
  709. target.emplace_back(hoveredHex);
  710. spells::BattleCast event(owner.curInt->cb.get(), caster, mode, spell);
  711. auto mechanics = spell->battleMechanics(&event);
  712. return mechanics->getAffectedStacks(target);
  713. }
  714. if(hoveredHex.isValid())
  715. {
  716. const CStack * const stack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  717. if (stack)
  718. return {stack};
  719. }
  720. return {};
  721. }
  722. const std::vector<uint32_t> BattleStacksController::getHoveredStacksUnitIds() const
  723. {
  724. auto result = std::vector<uint32_t>();
  725. for (auto const * stack : mouseHoveredStacks)
  726. {
  727. result.push_back(stack->unitId());
  728. }
  729. return result;
  730. }