BattleStacksController.cpp 29 KB

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