BattleStacksController.cpp 27 KB

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