BattleStacksController.cpp 27 KB

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