BattleStacksController.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. /*
  2. * BattleStacksController.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "BattleStacksController.h"
  12. #include "BattleSiegeController.h"
  13. #include "BattleInterfaceClasses.h"
  14. #include "BattleInterface.h"
  15. #include "BattleActionsController.h"
  16. #include "BattleAnimationClasses.h"
  17. #include "BattleFieldController.h"
  18. #include "BattleEffectsController.h"
  19. #include "BattleProjectileController.h"
  20. #include "BattleWindow.h"
  21. #include "BattleRenderer.h"
  22. #include "CreatureAnimation.h"
  23. #include "../CPlayerInterface.h"
  24. #include "../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, [=]()
  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, [=]()
  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. float health = stack->getMaxHealth();
  264. float healthRemaining = std::max(stack->getAvailableHealth() - (stack->getCount() - 1) * health, .0f);
  265. Rect r(boxPosition.x, boxPosition.y - 3, amountBG->width(), 4);
  266. canvas.drawColor(r, Colors::RED);
  267. canvas.drawColor(Rect(r.x, r.y, (r.w / health) * healthRemaining, r.h), Colors::GREEN);
  268. canvas.drawBorder(r, Colors::YELLOW);
  269. }
  270. canvas.draw(amountBG, boxPosition);
  271. canvas.drawText(textPosition, EFonts::FONT_TINY, Colors::WHITE, ETextAlignment::CENTER, TextOperations::formatMetric(stack->getCount(), 4));
  272. }
  273. void BattleStacksController::showStack(Canvas & canvas, const CStack * stack)
  274. {
  275. ColorRGBA effectColor = Colors::TRANSPARENCY;
  276. uint8_t transparency = 255;
  277. for(const auto & filter : stackFilterEffects)
  278. {
  279. if (filter.target == stack)
  280. {
  281. effectColor = filter.effectColor;
  282. transparency = static_cast<int>(filter.transparency) * transparency / 255;
  283. }
  284. }
  285. stackAnimation[stack->unitId()]->nextFrame(canvas, effectColor, transparency, facingRight(stack)); // do actual blit
  286. }
  287. void BattleStacksController::tick(uint32_t msPassed)
  288. {
  289. updateHoveredStacks();
  290. updateBattleAnimations(msPassed);
  291. }
  292. void BattleStacksController::initializeBattleAnimations()
  293. {
  294. auto copiedVector = currentAnimations;
  295. for (auto & elem : copiedVector)
  296. if (elem && !elem->isInitialized())
  297. elem->tryInitialize();
  298. }
  299. void BattleStacksController::tickFrameBattleAnimations(uint32_t msPassed)
  300. {
  301. for (auto stack : owner.getBattle()->battleGetAllStacks(true))
  302. {
  303. if (stackAnimation.find(stack->unitId()) == stackAnimation.end()) //e.g. for summoned but not yet handled stacks
  304. continue;
  305. stackAnimation[stack->unitId()]->incrementFrame(msPassed / 1000.f);
  306. }
  307. // operate on copy - to prevent potential iterator invalidation due to push_back's
  308. // FIXME? : remove remaining calls to addNewAnim from BattleAnimation::nextFrame (only Catapult explosion at the time of writing)
  309. auto copiedVector = currentAnimations;
  310. for (auto & elem : copiedVector)
  311. if (elem && elem->isInitialized())
  312. elem->tick(msPassed);
  313. }
  314. void BattleStacksController::updateBattleAnimations(uint32_t msPassed)
  315. {
  316. bool hadAnimations = !currentAnimations.empty();
  317. initializeBattleAnimations();
  318. tickFrameBattleAnimations(msPassed);
  319. vstd::erase(currentAnimations, nullptr);
  320. if (currentAnimations.empty())
  321. owner.executeStagedAnimations();
  322. if (hadAnimations && currentAnimations.empty())
  323. owner.onAnimationsFinished();
  324. initializeBattleAnimations();
  325. }
  326. void BattleStacksController::addNewAnim(BattleAnimation *anim)
  327. {
  328. if (currentAnimations.empty())
  329. stackAmountBoxHidden.clear();
  330. owner.onAnimationsStarted();
  331. currentAnimations.push_back(anim);
  332. auto stackAnimation = dynamic_cast<BattleStackAnimation*>(anim);
  333. if(stackAnimation)
  334. stackAmountBoxHidden.insert(stackAnimation->stack->unitId());
  335. }
  336. void BattleStacksController::stackRemoved(uint32_t stackID)
  337. {
  338. if (getActiveStack() && getActiveStack()->unitId() == stackID)
  339. setActiveStack(nullptr);
  340. }
  341. void BattleStacksController::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  342. {
  343. owner.addToAnimationStage(EAnimationEvents::HIT, [=](){
  344. // remove any potentially erased petrification effect
  345. removeExpiredColorFilters();
  346. });
  347. for(auto & attackedInfo : attackedInfos)
  348. {
  349. if (!attackedInfo.attacker)
  350. continue;
  351. // In H3, attacked stack will not reverse on ranged attack
  352. if (attackedInfo.indirectAttack)
  353. continue;
  354. // Another type of indirect attack - dragon breath
  355. if (!CStack::isMeleeAttackPossible(attackedInfo.attacker, attackedInfo.defender))
  356. continue;
  357. // defender need to face in direction opposited to out attacker
  358. bool needsReverse = shouldAttackFacingRight(attackedInfo.attacker, attackedInfo.defender) == facingRight(attackedInfo.defender);
  359. // FIXME: this check is better, however not usable since stacksAreAttacked is called after net pack is applied - petrification is already removed
  360. // if (needsReverse && !attackedInfo.defender->isFrozen())
  361. if (needsReverse && stackAnimation[attackedInfo.defender->unitId()]->getType() != ECreatureAnimType::FROZEN)
  362. {
  363. owner.addToAnimationStage(EAnimationEvents::MOVEMENT, [=]()
  364. {
  365. addNewAnim(new ReverseAnimation(owner, attackedInfo.defender, attackedInfo.defender->getPosition()));
  366. });
  367. }
  368. }
  369. for(auto & attackedInfo : attackedInfos)
  370. {
  371. bool useDeathAnim = attackedInfo.killed;
  372. bool useDefenceAnim = attackedInfo.defender->defendingAnim && !attackedInfo.indirectAttack && !attackedInfo.killed;
  373. EAnimationEvents usedEvent = useDefenceAnim ? EAnimationEvents::ATTACK : EAnimationEvents::HIT;
  374. owner.addToAnimationStage(usedEvent, [=]()
  375. {
  376. if (useDeathAnim)
  377. addNewAnim(new DeathAnimation(owner, attackedInfo.defender, attackedInfo.indirectAttack));
  378. else if(useDefenceAnim)
  379. addNewAnim(new DefenceAnimation(owner, attackedInfo.defender));
  380. else
  381. addNewAnim(new HittedAnimation(owner, attackedInfo.defender));
  382. if (attackedInfo.fireShield)
  383. owner.effectsController->displayEffect(EBattleEffect::FIRE_SHIELD, AudioPath::builtin("FIRESHIE"), attackedInfo.attacker->getPosition());
  384. if (attackedInfo.spellEffect != SpellID::NONE)
  385. {
  386. auto spell = attackedInfo.spellEffect.toSpell();
  387. if (!spell->getCastSound().empty())
  388. ENGINE->sound().playSound(spell->getCastSound());
  389. owner.displaySpellEffect(spell, attackedInfo.defender->getPosition());
  390. }
  391. });
  392. }
  393. for (auto & attackedInfo : attackedInfos)
  394. {
  395. if (attackedInfo.rebirth)
  396. {
  397. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  398. owner.effectsController->displayEffect(EBattleEffect::RESURRECT, AudioPath::builtin("RESURECT"), attackedInfo.defender->getPosition());
  399. addNewAnim(new ResurrectionAnimation(owner, attackedInfo.defender));
  400. });
  401. }
  402. if (attackedInfo.killed && attackedInfo.defender->summoned)
  403. {
  404. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  405. addNewAnim(new ColorTransformAnimation(owner, attackedInfo.defender, "summonFadeOut", nullptr));
  406. stackRemoved(attackedInfo.defender->unitId());
  407. });
  408. }
  409. }
  410. owner.executeStagedAnimations();
  411. owner.waitForAnimations();
  412. }
  413. void BattleStacksController::stackTeleported(const CStack *stack, const BattleHexArray & destHex, int distance)
  414. {
  415. assert(destHex.size() > 0);
  416. //owner.checkForAnimations(); // NOTE: at this point spellcast animations were added, but not executed
  417. owner.addToAnimationStage(EAnimationEvents::HIT, [=](){
  418. addNewAnim( new ColorTransformAnimation(owner, stack, "teleportFadeOut", nullptr) );
  419. });
  420. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=](){
  421. stackAnimation[stack->unitId()]->pos.moveTo(getStackPositionAtHex(destHex.back(), stack));
  422. addNewAnim( new ColorTransformAnimation(owner, stack, "teleportFadeIn", nullptr) );
  423. });
  424. // animations will be executed by spell
  425. }
  426. void BattleStacksController::stackMoved(const CStack *stack, const BattleHexArray & destHex, int distance)
  427. {
  428. assert(destHex.size() > 0);
  429. owner.checkForAnimations();
  430. if(shouldRotate(stack, stack->getPosition(), destHex[0]))
  431. {
  432. owner.addToAnimationStage(EAnimationEvents::ROTATE, [&]()
  433. {
  434. addNewAnim(new ReverseAnimation(owner, stack, stack->getPosition()));
  435. });
  436. }
  437. owner.addToAnimationStage(EAnimationEvents::MOVE_START, [&]()
  438. {
  439. addNewAnim(new MovementStartAnimation(owner, stack));
  440. });
  441. if (!stack->hasBonus(Selector::typeSubtype(BonusType::FLYING, BonusCustomSubtype::movementTeleporting)))
  442. {
  443. owner.addToAnimationStage(EAnimationEvents::MOVEMENT, [&]()
  444. {
  445. addNewAnim(new MovementAnimation(owner, stack, destHex, distance));
  446. });
  447. }
  448. owner.addToAnimationStage(EAnimationEvents::MOVE_END, [&]()
  449. {
  450. addNewAnim(new MovementEndAnimation(owner, stack, destHex.back()));
  451. });
  452. owner.executeStagedAnimations();
  453. owner.waitForAnimations();
  454. }
  455. bool BattleStacksController::shouldAttackFacingRight(const CStack * attacker, const CStack * defender)
  456. {
  457. bool mustReverse = owner.getBattle()->isToReverse(attacker, defender);
  458. if (attacker->unitSide() == BattleSide::ATTACKER)
  459. return !mustReverse;
  460. else
  461. return mustReverse;
  462. }
  463. void BattleStacksController::stackAttacking( const StackAttackInfo & info )
  464. {
  465. owner.checkForAnimations();
  466. auto attacker = info.attacker;
  467. auto defender = info.defender;
  468. auto tile = info.tile;
  469. auto spellEffect = info.spellEffect;
  470. auto multiAttack = !info.secondaryDefender.empty();
  471. bool needsReverse = false;
  472. if (info.indirectAttack)
  473. {
  474. needsReverse = shouldRotate(attacker, attacker->position, info.tile);
  475. }
  476. else
  477. {
  478. needsReverse = shouldAttackFacingRight(attacker, defender) != facingRight(attacker);
  479. }
  480. if (needsReverse)
  481. {
  482. owner.addToAnimationStage(EAnimationEvents::MOVEMENT, [=]()
  483. {
  484. addNewAnim(new ReverseAnimation(owner, attacker, attacker->getPosition()));
  485. });
  486. }
  487. if(info.lucky)
  488. {
  489. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  490. owner.appendBattleLog(info.attacker->formatGeneralMessage(-45));
  491. owner.effectsController->displayEffect(EBattleEffect::GOOD_LUCK, AudioPath::builtin("GOODLUCK"), attacker->getPosition());
  492. });
  493. }
  494. if(info.unlucky)
  495. {
  496. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  497. owner.appendBattleLog(info.attacker->formatGeneralMessage(-44));
  498. owner.effectsController->displayEffect(EBattleEffect::BAD_LUCK, AudioPath::builtin("BADLUCK"), attacker->getPosition());
  499. });
  500. }
  501. if(info.deathBlow)
  502. {
  503. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  504. owner.appendBattleLog(info.attacker->formatGeneralMessage(365));
  505. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, AudioPath::builtin("DEATHBLO"), defender->getPosition());
  506. });
  507. for(auto elem : info.secondaryDefender)
  508. {
  509. owner.addToAnimationStage(EAnimationEvents::BEFORE_HIT, [=]() {
  510. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, elem->getPosition());
  511. });
  512. }
  513. }
  514. owner.addToAnimationStage(EAnimationEvents::ATTACK, [=]()
  515. {
  516. if (info.indirectAttack)
  517. {
  518. addNewAnim(new ShootingAnimation(owner, attacker, tile, defender));
  519. }
  520. else
  521. {
  522. addNewAnim(new MeleeAttackAnimation(owner, attacker, tile, defender, multiAttack));
  523. }
  524. });
  525. if (info.spellEffect != SpellID::NONE)
  526. {
  527. owner.addToAnimationStage(EAnimationEvents::HIT, [=]()
  528. {
  529. owner.displaySpellHit(spellEffect.toSpell(), tile);
  530. });
  531. }
  532. if (info.lifeDrain)
  533. {
  534. owner.addToAnimationStage(EAnimationEvents::AFTER_HIT, [=]()
  535. {
  536. owner.effectsController->displayEffect(EBattleEffect::DRAIN_LIFE, AudioPath::builtin("DRAINLIF"), attacker->getPosition(), 0.5);
  537. });
  538. }
  539. //return, animation playback will be handled by stacksAreAttacked
  540. }
  541. bool BattleStacksController::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex) const
  542. {
  543. Point begPosition = getStackPositionAtHex(oldPos,stack);
  544. Point endPosition = getStackPositionAtHex(nextHex, stack);
  545. if((begPosition.x > endPosition.x) && facingRight(stack))
  546. return true;
  547. else if((begPosition.x < endPosition.x) && !facingRight(stack))
  548. return true;
  549. return false;
  550. }
  551. void BattleStacksController::endAction(const BattleAction & action)
  552. {
  553. owner.checkForAnimations();
  554. //check if we should reverse stacks
  555. TStacks stacks = owner.getBattle()->battleGetStacks(CPlayerBattleCallback::MINE_AND_ENEMY);
  556. for (const CStack *s : stacks)
  557. {
  558. bool shouldFaceRight = s && s->unitSide() == BattleSide::ATTACKER;
  559. if (s && facingRight(s) != shouldFaceRight && s->alive() && stackAnimation[s->unitId()]->isIdle())
  560. {
  561. addNewAnim(new ReverseAnimation(owner, s, s->getPosition()));
  562. }
  563. }
  564. owner.executeStagedAnimations();
  565. owner.waitForAnimations();
  566. stackAmountBoxHidden.clear();
  567. owner.windowObject->blockUI(activeStack == nullptr);
  568. removeExpiredColorFilters();
  569. }
  570. void BattleStacksController::startAction(const BattleAction & action)
  571. {
  572. // if timer run out and we did not act in time - deactivate current stack
  573. setActiveStack(nullptr);
  574. removeExpiredColorFilters();
  575. }
  576. void BattleStacksController::stackActivated(const CStack *stack)
  577. {
  578. stackToActivate = stack;
  579. owner.waitForAnimations();
  580. logAnim->debug("Activating next stack");
  581. owner.activateStack();
  582. }
  583. void BattleStacksController::deactivateStack()
  584. {
  585. if (!activeStack) {
  586. return;
  587. }
  588. stackToActivate = activeStack;
  589. setActiveStack(nullptr);
  590. }
  591. void BattleStacksController::activateStack()
  592. {
  593. if ( !currentAnimations.empty())
  594. return;
  595. if ( !stackToActivate)
  596. return;
  597. owner.trySetActivePlayer(stackToActivate->unitOwner());
  598. setActiveStack(stackToActivate);
  599. stackToActivate = nullptr;
  600. const CStack * s = getActiveStack();
  601. if(!s)
  602. return;
  603. }
  604. const CStack* BattleStacksController::getActiveStack() const
  605. {
  606. return activeStack;
  607. }
  608. bool BattleStacksController::facingRight(const CStack * stack) const
  609. {
  610. return stackFacingRight.at(stack->unitId());
  611. }
  612. Point BattleStacksController::getStackPositionAtHex(const BattleHex & hexNum, const CStack * stack) const
  613. {
  614. Point ret(-500, -500); //returned value
  615. if(stack && stack->initialPosition < 0) //creatures in turrets
  616. return owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  617. static const Point basePos(-189, -139); // position of creature in topleft corner
  618. static const int imageShiftX = 29; // X offset to base pos for facing right stacks, negative for facing left
  619. ret.x = basePos.x + 22 * ( (hexNum.getY() + 1)%2 ) + 44 * hexNum.getX();
  620. ret.y = basePos.y + 42 * hexNum.getY();
  621. if (stack)
  622. {
  623. if(facingRight(stack))
  624. ret.x += imageShiftX;
  625. else
  626. ret.x -= imageShiftX;
  627. //shifting position for double - hex creatures
  628. if(stack->doubleWide())
  629. {
  630. if(stack->unitSide() == BattleSide::ATTACKER)
  631. {
  632. if(facingRight(stack))
  633. ret.x -= 44;
  634. }
  635. else
  636. {
  637. if(!facingRight(stack))
  638. ret.x += 44;
  639. }
  640. }
  641. }
  642. //returning
  643. return ret;
  644. }
  645. void BattleStacksController::setStackColorFilter(const ColorRGBA & effectColor, uint8_t transparency, const CStack * target, const CSpell * source, bool persistent)
  646. {
  647. for (auto & filter : stackFilterEffects)
  648. {
  649. if (filter.target == target && filter.source == source)
  650. {
  651. filter.effectColor = effectColor;
  652. filter.transparency = transparency;
  653. filter.persistent = persistent;
  654. return;
  655. }
  656. }
  657. stackFilterEffects.push_back({ target, source, effectColor, transparency, persistent });
  658. }
  659. void BattleStacksController::removeExpiredColorFilters()
  660. {
  661. vstd::erase_if(stackFilterEffects, [&](const BattleStackFilterEffect & filter)
  662. {
  663. if (!filter.persistent)
  664. {
  665. if (filter.source && !filter.target->hasBonus(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(filter.source->id)), Selector::all))
  666. return true;
  667. if (filter.effectColor == Colors::TRANSPARENCY && filter.transparency == 255)
  668. return true;
  669. }
  670. return false;
  671. });
  672. }
  673. void BattleStacksController::updateHoveredStacks()
  674. {
  675. auto newStacks = selectHoveredStacks();
  676. if(newStacks.size() == 0)
  677. owner.windowObject->updateStackInfoWindow(nullptr);
  678. for(const auto * stack : mouseHoveredStacks)
  679. {
  680. if (vstd::contains(newStacks, stack))
  681. continue;
  682. if (stack == activeStack)
  683. stackAnimation[stack->unitId()]->setBorderColor(AnimationControls::getGoldBorder());
  684. else
  685. stackAnimation[stack->unitId()]->setBorderColor(AnimationControls::getNoBorder());
  686. }
  687. for(const auto * stack : newStacks)
  688. {
  689. if (vstd::contains(mouseHoveredStacks, stack))
  690. continue;
  691. owner.windowObject->updateStackInfoWindow(newStacks.size() == 1 && vstd::find_pos(newStacks, stack) == 0 ? stack : nullptr);
  692. stackAnimation[stack->unitId()]->setBorderColor(AnimationControls::getBlueBorder());
  693. if (stackAnimation[stack->unitId()]->framesInGroup(ECreatureAnimType::MOUSEON) > 0 && stack->alive() && !stack->isFrozen())
  694. stackAnimation[stack->unitId()]->playOnce(ECreatureAnimType::MOUSEON);
  695. }
  696. if(mouseHoveredStacks != newStacks)
  697. ENGINE->windows().totalRedraw(); //fix for frozen stack info window and blue border in action bar
  698. mouseHoveredStacks = newStacks;
  699. }
  700. std::vector<const CStack *> BattleStacksController::selectHoveredStacks()
  701. {
  702. // only allow during our turn - do not try to highlight creatures while they are in the middle of actions
  703. if (!activeStack)
  704. return {};
  705. if(owner.hasAnimations())
  706. return {};
  707. auto hoveredQueueUnitId = owner.windowObject->getQueueHoveredUnitId();
  708. if(hoveredQueueUnitId.has_value())
  709. {
  710. return { owner.getBattle()->battleGetStackByID(hoveredQueueUnitId.value(), true) };
  711. }
  712. auto hoveredHex = owner.fieldController->getHoveredHex();
  713. if (!hoveredHex.isValid())
  714. return {};
  715. const spells::Caster *caster = nullptr;
  716. const CSpell *spell = nullptr;
  717. spells::Mode mode = owner.actionsController->getCurrentCastMode();
  718. spell = owner.actionsController->getCurrentSpell(hoveredHex);
  719. caster = owner.actionsController->getCurrentSpellcaster();
  720. //casting spell or in explicit spellcasting mode that also handles SPELL_LIKE_ATTACK
  721. if(caster && spell && (owner.actionsController->currentActionSpellcasting(hoveredHex) || owner.actionsController->creatureSpellcastingModeActive()))
  722. {
  723. spells::Target target;
  724. target.emplace_back(hoveredHex);
  725. spells::BattleCast event(owner.getBattle().get(), caster, mode, spell);
  726. auto mechanics = spell->battleMechanics(&event);
  727. return mechanics->getAffectedStacks(target);
  728. }
  729. if(hoveredHex.isValid())
  730. {
  731. const CStack * const stack = owner.getBattle()->battleGetStackByPos(hoveredHex, true);
  732. if (stack)
  733. return {stack};
  734. }
  735. return {};
  736. }
  737. const std::vector<uint32_t> BattleStacksController::getHoveredStacksUnitIds() const
  738. {
  739. auto result = std::vector<uint32_t>();
  740. for(const auto * stack : mouseHoveredStacks)
  741. {
  742. result.push_back(stack->unitId());
  743. }
  744. return result;
  745. }