BattleStacksController.cpp 28 KB

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