BattleStacksController.cpp 27 KB

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