BattleStacksController.cpp 27 KB

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