BattleStacksController.cpp 28 KB

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