BattleStacksController.cpp 27 KB

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