BattleStacksController.cpp 27 KB

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