BattleStacksController.cpp 27 KB

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