BattleStacksController.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  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 "BattleControlPanel.h"
  21. #include "BattleRenderer.h"
  22. #include "CreatureAnimation.h"
  23. #include "../CPlayerInterface.h"
  24. #include "../CMusicHandler.h"
  25. #include "../CGameInfo.h"
  26. #include "../gui/CAnimation.h"
  27. #include "../gui/CGuiHandler.h"
  28. #include "../gui/Canvas.h"
  29. #include "../../lib/spells/ISpellMechanics.h"
  30. #include "../../CCallback.h"
  31. #include "../../lib/battle/BattleHex.h"
  32. #include "../../lib/CGameState.h"
  33. #include "../../lib/CStack.h"
  34. #include "../../lib/CondSh.h"
  35. static void onAnimationFinished(const CStack *stack, std::weak_ptr<CreatureAnimation> anim)
  36. {
  37. std::shared_ptr<CreatureAnimation> animation = anim.lock();
  38. if(!animation)
  39. return;
  40. if (!stack->isFrozen() && animation->getType() == ECreatureAnimType::FROZEN)
  41. animation->setType(ECreatureAnimType::HOLDING);
  42. if (animation->isIdle())
  43. {
  44. if (stack->isFrozen())
  45. animation->setType(ECreatureAnimType::FROZEN);
  46. const CCreature *creature = stack->getCreature();
  47. if (animation->framesInGroup(ECreatureAnimType::MOUSEON) > 0)
  48. {
  49. if (CRandomGenerator::getDefault().nextDouble(99.0) < creature->animation.timeBetweenFidgets *10)
  50. animation->playOnce(ECreatureAnimType::MOUSEON);
  51. else
  52. animation->setType(ECreatureAnimType::HOLDING);
  53. }
  54. else
  55. {
  56. animation->setType(ECreatureAnimType::HOLDING);
  57. }
  58. }
  59. // always reset callback
  60. animation->onAnimationReset += std::bind(&onAnimationFinished, stack, anim);
  61. }
  62. BattleStacksController::BattleStacksController(BattleInterface & owner):
  63. owner(owner),
  64. activeStack(nullptr),
  65. stackToActivate(nullptr),
  66. selectedStack(nullptr),
  67. stackCanCastSpell(false),
  68. creatureSpellToCast(uint32_t(-1)),
  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,0,0, 0.6, 0.2, 1.0 );
  77. static const auto shifterPositive = ColorFilter::genRangeShifter( 0,0,0, 0.2, 1.0, 0.2 );
  78. static const auto shifterNegative = ColorFilter::genRangeShifter( 0,0,0, 1.0, 0.2, 0.2 );
  79. static const auto shifterNeutral = ColorFilter::genRangeShifter( 0,0,0, 1.0, 1.0, 0.2 );
  80. amountNormal->adjustPalette(shifterNormal);
  81. amountPositive->adjustPalette(shifterPositive);
  82. amountNegative->adjustPalette(shifterNegative);
  83. amountEffNeutral->adjustPalette(shifterNeutral);
  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(ColorTransformAnimation::fadeInAnimation(owner, stack));
  190. if (stack->isClone())
  191. addNewAnim(ColorTransformAnimation::cloneAnimation(owner, stack, 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.controlPanel->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. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->getCount() == 1) //do not show box for singular war machines, stacked war machines with box shown are supported as extension feature
  214. return false;
  215. if(!stack->alive())
  216. return false;
  217. if(stack->getCount() == 0) //hide box when target is going to die anyway - do not display "0 creatures"
  218. return false;
  219. for(auto anim : currentAnimations) //no matter what other conditions below are, hide box when creature is playing hit animation
  220. {
  221. auto hitAnimation = dynamic_cast<DefenceAnimation*>(anim);
  222. if(hitAnimation && (hitAnimation->stack->ID == stack->ID))
  223. return false;
  224. }
  225. if(owner.curInt->curAction)
  226. {
  227. if(owner.curInt->curAction->stackNumber == stack->ID) //stack is currently taking action (is not a target of another creature's action etc)
  228. {
  229. if(owner.curInt->curAction->actionType == EActionType::WALK || owner.curInt->curAction->actionType == EActionType::SHOOT) //hide when stack walks or shoots
  230. return false;
  231. else if(owner.curInt->curAction->actionType == EActionType::WALK_AND_ATTACK && currentActionTarget != stack->getPosition()) //when attacking, hide until walk phase finished
  232. return false;
  233. }
  234. if(owner.curInt->curAction->actionType == EActionType::SHOOT && currentActionTarget == stack->getPosition()) //hide if we are ranged attack target
  235. return false;
  236. }
  237. return true;
  238. }
  239. std::shared_ptr<IImage> BattleStacksController::getStackAmountBox(const CStack * stack)
  240. {
  241. std::vector<si32> activeSpells = stack->activeSpells();
  242. if ( activeSpells.empty())
  243. return amountNormal;
  244. int effectsPositivness = 0;
  245. for ( auto const & spellID : activeSpells)
  246. effectsPositivness += CGI->spellh->objects.at(spellID)->positiveness;
  247. if (effectsPositivness > 0)
  248. return amountPositive;
  249. if (effectsPositivness < 0)
  250. return amountNegative;
  251. return amountEffNeutral;
  252. }
  253. void BattleStacksController::showStackAmountBox(Canvas & canvas, const CStack * stack)
  254. {
  255. //blitting amount background box
  256. auto amountBG = getStackAmountBox(stack);
  257. const int sideShift = stack->side == BattleSide::ATTACKER ? 1 : -1;
  258. const int reverseSideShift = stack->side == BattleSide::ATTACKER ? -1 : 1;
  259. const BattleHex nextPos = stack->getPosition() + sideShift;
  260. const bool edge = stack->getPosition() % GameConstants::BFIELD_WIDTH == (stack->side == BattleSide::ATTACKER ? GameConstants::BFIELD_WIDTH - 2 : 1);
  261. const bool moveInside = !edge && !owner.fieldController->stackCountOutsideHex(nextPos);
  262. int xAdd = (stack->side == BattleSide::ATTACKER ? 220 : 202) +
  263. (stack->doubleWide() ? 44 : 0) * sideShift +
  264. (moveInside ? amountBG->width() + 10 : 0) * reverseSideShift;
  265. int yAdd = 260 + ((stack->side == BattleSide::ATTACKER || moveInside) ? 0 : -15);
  266. canvas.draw(amountBG, stackAnimation[stack->ID]->pos.topLeft() + Point(xAdd, yAdd));
  267. //blitting amount
  268. Point textPos = stackAnimation[stack->ID]->pos.topLeft() + amountBG->dimensions()/2 + Point(xAdd, yAdd);
  269. canvas.drawText(textPos, EFonts::FONT_TINY, Colors::WHITE, ETextAlignment::CENTER, makeNumberShort(stack->getCount()));
  270. }
  271. void BattleStacksController::showStack(Canvas & canvas, const CStack * stack)
  272. {
  273. ColorFilter fullFilter = ColorFilter::genEmptyShifter();
  274. for (auto const & filter : stackFilterEffects)
  275. {
  276. if (filter.target == stack)
  277. fullFilter = ColorFilter::genCombined(fullFilter, filter.effect);
  278. }
  279. bool stackHasProjectile = owner.projectilesController->hasActiveProjectile(stack, true);
  280. if (stackHasProjectile)
  281. stackAnimation[stack->ID]->pause();
  282. else
  283. stackAnimation[stack->ID]->play();
  284. stackAnimation[stack->ID]->nextFrame(canvas, fullFilter, facingRight(stack)); // do actual blit
  285. stackAnimation[stack->ID]->incrementFrame(float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000);
  286. }
  287. void BattleStacksController::update()
  288. {
  289. updateHoveredStacks();
  290. updateBattleAnimations();
  291. }
  292. void BattleStacksController::updateBattleAnimations()
  293. {
  294. for (auto & elem : currentAnimations)
  295. {
  296. if (!elem)
  297. continue;
  298. if (elem->isInitialized())
  299. elem->nextFrame();
  300. else
  301. elem->tryInitialize();
  302. }
  303. bool hadAnimations = !currentAnimations.empty();
  304. vstd::erase(currentAnimations, nullptr);
  305. if (hadAnimations && currentAnimations.empty())
  306. {
  307. //anims ended
  308. owner.setAnimationCondition(EAnimationEvents::ACTION, false);
  309. }
  310. }
  311. void BattleStacksController::addNewAnim(BattleAnimation *anim)
  312. {
  313. currentAnimations.push_back(anim);
  314. owner.setAnimationCondition(EAnimationEvents::ACTION, true);
  315. }
  316. void BattleStacksController::stackRemoved(uint32_t stackID)
  317. {
  318. if (getActiveStack() && getActiveStack()->ID == stackID)
  319. {
  320. BattleAction *action = new BattleAction();
  321. action->side = owner.defendingHeroInstance ? (owner.curInt->playerID == owner.defendingHeroInstance->tempOwner) : false;
  322. action->actionType = EActionType::CANCEL;
  323. action->stackNumber = getActiveStack()->ID;
  324. owner.givenCommand.setn(action);
  325. setActiveStack(nullptr);
  326. }
  327. }
  328. void BattleStacksController::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  329. {
  330. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=](){
  331. // remove any potentially erased petrification effect
  332. removeExpiredColorFilters();
  333. });
  334. for(auto & attackedInfo : attackedInfos)
  335. {
  336. if (!attackedInfo.attacker)
  337. continue;
  338. // In H3, attacked stack will not reverse on ranged attack
  339. if (attackedInfo.indirectAttack)
  340. continue;
  341. // defender need to face in direction opposited to out attacker
  342. bool needsReverse = shouldAttackFacingRight(attackedInfo.attacker, attackedInfo.defender) == facingRight(attackedInfo.defender);
  343. if (needsReverse && !attackedInfo.defender->isFrozen())
  344. {
  345. owner.executeOnAnimationCondition(EAnimationEvents::MOVEMENT, true, [=]()
  346. {
  347. addNewAnim(new ReverseAnimation(owner, attackedInfo.defender, attackedInfo.defender->getPosition()));
  348. });
  349. }
  350. }
  351. for(auto & attackedInfo : attackedInfos)
  352. {
  353. bool useDeathAnim = attackedInfo.killed;
  354. bool useDefenceAnim = attackedInfo.defender->defendingAnim && !attackedInfo.indirectAttack && !attackedInfo.killed;
  355. EAnimationEvents usedEvent = useDefenceAnim ? EAnimationEvents::ATTACK : EAnimationEvents::HIT;
  356. owner.executeOnAnimationCondition(usedEvent, true, [=]()
  357. {
  358. if (useDeathAnim)
  359. addNewAnim(new DeathAnimation(owner, attackedInfo.defender, attackedInfo.indirectAttack));
  360. else if(useDefenceAnim)
  361. addNewAnim(new DefenceAnimation(owner, attackedInfo.defender));
  362. else
  363. addNewAnim(new HittedAnimation(owner, attackedInfo.defender));
  364. if (attackedInfo.fireShield)
  365. owner.effectsController->displayEffect(EBattleEffect::FIRE_SHIELD, attackedInfo.attacker->getPosition());
  366. if (attackedInfo.spellEffect != SpellID::NONE)
  367. owner.displaySpellEffect(attackedInfo.spellEffect, attackedInfo.defender->getPosition());
  368. });
  369. }
  370. for (auto & attackedInfo : attackedInfos)
  371. {
  372. if (attackedInfo.rebirth)
  373. {
  374. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  375. owner.effectsController->displayEffect(EBattleEffect::RESURRECT, soundBase::RESURECT, attackedInfo.defender->getPosition());
  376. addNewAnim(new ResurrectionAnimation(owner, attackedInfo.defender));
  377. });
  378. }
  379. if (attackedInfo.killed && attackedInfo.defender->summoned)
  380. {
  381. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=](){
  382. addNewAnim(ColorTransformAnimation::fadeOutAnimation(owner, attackedInfo.defender));
  383. stackRemoved(attackedInfo.defender->ID);
  384. });
  385. }
  386. }
  387. executeAttackAnimations();
  388. }
  389. void BattleStacksController::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  390. {
  391. assert(destHex.size() > 0);
  392. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  393. if(shouldRotate(stack, stack->getPosition(), destHex[0]))
  394. {
  395. addNewAnim(new ReverseAnimation(owner, stack, stack->getPosition()));
  396. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  397. }
  398. addNewAnim(new MovementStartAnimation(owner, stack));
  399. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  400. addNewAnim(new MovementAnimation(owner, stack, destHex, distance));
  401. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  402. addNewAnim(new MovementEndAnimation(owner, stack, destHex.back()));
  403. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  404. }
  405. bool BattleStacksController::shouldAttackFacingRight(const CStack * attacker, const CStack * defender)
  406. {
  407. bool mustReverse = owner.curInt->cb->isToReverse(
  408. attacker->getPosition(),
  409. attacker,
  410. defender);
  411. if (attacker->side == BattleSide::ATTACKER)
  412. return !mustReverse;
  413. else
  414. return mustReverse;
  415. }
  416. void BattleStacksController::stackAttacking( const StackAttackInfo & info )
  417. {
  418. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  419. auto attacker = info.attacker;
  420. auto defender = info.defender;
  421. auto tile = info.tile;
  422. auto spellEffect = info.spellEffect;
  423. auto multiAttack = !info.secondaryDefender.empty();
  424. bool needsReverse = false;
  425. if (info.indirectAttack)
  426. {
  427. needsReverse = shouldRotate(attacker, attacker->position, info.tile);
  428. }
  429. else
  430. {
  431. needsReverse = shouldAttackFacingRight(attacker, defender) != facingRight(attacker);
  432. }
  433. if (needsReverse)
  434. {
  435. owner.executeOnAnimationCondition(EAnimationEvents::MOVEMENT, true, [=]()
  436. {
  437. addNewAnim(new ReverseAnimation(owner, attacker, attacker->getPosition()));
  438. });
  439. }
  440. if(info.lucky)
  441. {
  442. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  443. owner.controlPanel->console->addText(info.attacker->formatGeneralMessage(-45));
  444. owner.effectsController->displayEffect(EBattleEffect::GOOD_LUCK, soundBase::GOODLUCK, attacker->getPosition());
  445. });
  446. }
  447. if(info.unlucky)
  448. {
  449. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  450. owner.controlPanel->console->addText(info.attacker->formatGeneralMessage(-44));
  451. owner.effectsController->displayEffect(EBattleEffect::BAD_LUCK, soundBase::BADLUCK, attacker->getPosition());
  452. });
  453. }
  454. if(info.deathBlow)
  455. {
  456. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  457. owner.controlPanel->console->addText(info.attacker->formatGeneralMessage(365));
  458. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, soundBase::deathBlow, defender->getPosition());
  459. });
  460. for(auto elem : info.secondaryDefender)
  461. {
  462. owner.executeOnAnimationCondition(EAnimationEvents::BEFORE_HIT, true, [=]() {
  463. owner.effectsController->displayEffect(EBattleEffect::DEATH_BLOW, elem->getPosition());
  464. });
  465. }
  466. }
  467. owner.executeOnAnimationCondition(EAnimationEvents::ATTACK, true, [=]()
  468. {
  469. if (info.indirectAttack)
  470. {
  471. addNewAnim(new ShootingAnimation(owner, attacker, tile, defender));
  472. }
  473. else
  474. {
  475. addNewAnim(new MeleeAttackAnimation(owner, attacker, tile, defender, multiAttack));
  476. }
  477. });
  478. if (info.spellEffect != SpellID::NONE)
  479. {
  480. owner.executeOnAnimationCondition(EAnimationEvents::HIT, true, [=]()
  481. {
  482. owner.displaySpellHit(spellEffect, tile);
  483. });
  484. }
  485. if (info.lifeDrain)
  486. {
  487. owner.executeOnAnimationCondition(EAnimationEvents::AFTER_HIT, true, [=]()
  488. {
  489. owner.effectsController->displayEffect(EBattleEffect::DRAIN_LIFE, soundBase::DRAINLIF, attacker->getPosition());
  490. });
  491. }
  492. //return, animation playback will be handled by stacksAreAttacked
  493. }
  494. void BattleStacksController::executeAttackAnimations()
  495. {
  496. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, true);
  497. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  498. owner.setAnimationCondition(EAnimationEvents::MOVEMENT, false);
  499. owner.setAnimationCondition(EAnimationEvents::BEFORE_HIT, true);
  500. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  501. owner.setAnimationCondition(EAnimationEvents::BEFORE_HIT, false);
  502. owner.setAnimationCondition(EAnimationEvents::ATTACK, true);
  503. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  504. owner.setAnimationCondition(EAnimationEvents::ATTACK, false);
  505. // Note that HIT event can also be emitted by attack animation
  506. owner.setAnimationCondition(EAnimationEvents::HIT, true);
  507. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  508. owner.setAnimationCondition(EAnimationEvents::HIT, false);
  509. owner.setAnimationCondition(EAnimationEvents::AFTER_HIT, true);
  510. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  511. owner.setAnimationCondition(EAnimationEvents::AFTER_HIT, false);
  512. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  513. }
  514. bool BattleStacksController::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex) const
  515. {
  516. Point begPosition = getStackPositionAtHex(oldPos,stack);
  517. Point endPosition = getStackPositionAtHex(nextHex, stack);
  518. if((begPosition.x > endPosition.x) && facingRight(stack))
  519. return true;
  520. else if((begPosition.x < endPosition.x) && !facingRight(stack))
  521. return true;
  522. return false;
  523. }
  524. void BattleStacksController::endAction(const BattleAction* action)
  525. {
  526. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  527. //check if we should reverse stacks
  528. TStacks stacks = owner.curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
  529. for (const CStack *s : stacks)
  530. {
  531. bool shouldFaceRight = s && s->side == BattleSide::ATTACKER;
  532. if (s && facingRight(s) != shouldFaceRight && s->alive() && stackAnimation[s->ID]->isIdle())
  533. {
  534. addNewAnim(new ReverseAnimation(owner, s, s->getPosition()));
  535. }
  536. }
  537. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  538. //Ensure that all animation flags were reset
  539. assert(owner.getAnimationCondition(EAnimationEvents::OPENING) == false);
  540. assert(owner.getAnimationCondition(EAnimationEvents::ACTION) == false);
  541. assert(owner.getAnimationCondition(EAnimationEvents::MOVEMENT) == false);
  542. assert(owner.getAnimationCondition(EAnimationEvents::ATTACK) == false);
  543. assert(owner.getAnimationCondition(EAnimationEvents::HIT) == false);
  544. assert(owner.getAnimationCondition(EAnimationEvents::PROJECTILES) == false);
  545. owner.controlPanel->blockUI(activeStack == nullptr);
  546. removeExpiredColorFilters();
  547. }
  548. void BattleStacksController::startAction(const BattleAction* action)
  549. {
  550. removeExpiredColorFilters();
  551. }
  552. void BattleStacksController::stackActivated(const CStack *stack) //TODO: check it all before game state is changed due to abilities
  553. {
  554. stackToActivate = stack;
  555. owner.waitForAnimationCondition(EAnimationEvents::ACTION, false);
  556. owner.activateStack();
  557. }
  558. void BattleStacksController::activateStack() //TODO: check it all before game state is changed due to abilities
  559. {
  560. if ( !currentAnimations.empty())
  561. return;
  562. if ( !stackToActivate)
  563. return;
  564. owner.trySetActivePlayer(stackToActivate->owner);
  565. setActiveStack(stackToActivate);
  566. stackToActivate = nullptr;
  567. const CStack * s = getActiveStack();
  568. if(!s)
  569. return;
  570. //set casting flag to true if creature can use it to not check it every time
  571. const auto spellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::SPELLCASTER));
  572. const auto randomSpellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::RANDOM_SPELLCASTER));
  573. if(s->canCast() && (spellcaster || randomSpellcaster))
  574. {
  575. stackCanCastSpell = true;
  576. if(randomSpellcaster)
  577. creatureSpellToCast = -1; //spell will be set later on cast
  578. else
  579. creatureSpellToCast = owner.curInt->cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), s, CBattleInfoCallback::RANDOM_AIMED); //faerie dragon can cast only one spell until their next move
  580. //TODO: what if creature can cast BOTH random genie spell and aimed spell?
  581. //TODO: faerie dragon type spell should be selected by server
  582. }
  583. else
  584. {
  585. stackCanCastSpell = false;
  586. creatureSpellToCast = -1;
  587. }
  588. }
  589. void BattleStacksController::setSelectedStack(const CStack *stack)
  590. {
  591. selectedStack = stack;
  592. }
  593. const CStack* BattleStacksController::getSelectedStack() const
  594. {
  595. return selectedStack;
  596. }
  597. const CStack* BattleStacksController::getActiveStack() const
  598. {
  599. return activeStack;
  600. }
  601. bool BattleStacksController::facingRight(const CStack * stack) const
  602. {
  603. return stackFacingRight.at(stack->ID);
  604. }
  605. bool BattleStacksController::activeStackSpellcaster()
  606. {
  607. return stackCanCastSpell;
  608. }
  609. SpellID BattleStacksController::activeStackSpellToCast()
  610. {
  611. if (!stackCanCastSpell)
  612. return SpellID::NONE;
  613. return SpellID(creatureSpellToCast);
  614. }
  615. Point BattleStacksController::getStackPositionAtHex(BattleHex hexNum, const CStack * stack) const
  616. {
  617. Point ret(-500, -500); //returned value
  618. if(stack && stack->initialPosition < 0) //creatures in turrets
  619. return owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
  620. static const Point basePos(-190, -139); // position of creature in topleft corner
  621. static const int imageShiftX = 30; // X offset to base pos for facing right stacks, negative for facing left
  622. ret.x = basePos.x + 22 * ( (hexNum.getY() + 1)%2 ) + 44 * hexNum.getX();
  623. ret.y = basePos.y + 42 * hexNum.getY();
  624. if (stack)
  625. {
  626. if(facingRight(stack))
  627. ret.x += imageShiftX;
  628. else
  629. ret.x -= imageShiftX;
  630. //shifting position for double - hex creatures
  631. if(stack->doubleWide())
  632. {
  633. if(stack->side == BattleSide::ATTACKER)
  634. {
  635. if(facingRight(stack))
  636. ret.x -= 44;
  637. }
  638. else
  639. {
  640. if(!facingRight(stack))
  641. ret.x += 44;
  642. }
  643. }
  644. }
  645. //returning
  646. return ret + owner.pos.topLeft();
  647. }
  648. void BattleStacksController::setStackColorFilter(const ColorFilter & effect, const CStack * target, const CSpell * source, bool persistent)
  649. {
  650. for (auto & filter : stackFilterEffects)
  651. {
  652. if (filter.target == target && filter.source == source)
  653. {
  654. filter.effect = effect;
  655. filter.persistent = persistent;
  656. return;
  657. }
  658. }
  659. stackFilterEffects.push_back({ effect, target, source, persistent });
  660. }
  661. void BattleStacksController::removeExpiredColorFilters()
  662. {
  663. vstd::erase_if(stackFilterEffects, [&](const BattleStackFilterEffect & filter)
  664. {
  665. if (filter.persistent)
  666. return false;
  667. if (filter.effect == ColorFilter::genEmptyShifter())
  668. return false;
  669. if (filter.target->hasBonus(Selector::source(Bonus::SPELL_EFFECT, filter.source->id)))
  670. return false;
  671. return true;
  672. });
  673. }
  674. void BattleStacksController::updateHoveredStacks()
  675. {
  676. auto newStacks = selectHoveredStacks();
  677. for (auto const * stack : mouseHoveredStacks)
  678. {
  679. if (vstd::contains(newStacks, stack))
  680. continue;
  681. if (stack == activeStack)
  682. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  683. else
  684. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getNoBorder());
  685. }
  686. for (auto const * stack : newStacks)
  687. {
  688. if (vstd::contains(mouseHoveredStacks, stack))
  689. continue;
  690. stackAnimation[stack->ID]->setBorderColor(AnimationControls::getBlueBorder());
  691. if (stackAnimation[stack->ID]->framesInGroup(ECreatureAnimType::MOUSEON) > 0)
  692. stackAnimation[stack->ID]->playOnce(ECreatureAnimType::MOUSEON);
  693. }
  694. mouseHoveredStacks = newStacks;
  695. }
  696. std::vector<const CStack *> BattleStacksController::selectHoveredStacks()
  697. {
  698. auto hoveredHex = owner.fieldController->getHoveredHex();
  699. if (!hoveredHex.isValid())
  700. return {};
  701. const spells::Caster *caster = nullptr;
  702. const CSpell *spell = nullptr;
  703. spells::Mode mode = spells::Mode::HERO;
  704. if(owner.actionsController->spellcastingModeActive())//hero casts spell
  705. {
  706. spell = owner.actionsController->selectedSpell().toSpell();
  707. caster = owner.getActiveHero();
  708. }
  709. else if(owner.stacksController->activeStackSpellToCast() != SpellID::NONE)//stack casts spell
  710. {
  711. spell = SpellID(owner.stacksController->activeStackSpellToCast()).toSpell();
  712. caster = owner.stacksController->getActiveStack();
  713. mode = spells::Mode::CREATURE_ACTIVE;
  714. }
  715. if(caster && spell) //when casting spell
  716. {
  717. spells::Target target;
  718. target.emplace_back(hoveredHex);
  719. spells::BattleCast event(owner.curInt->cb.get(), caster, mode, spell);
  720. auto mechanics = spell->battleMechanics(&event);
  721. return mechanics->getAffectedStacks(target);
  722. }
  723. if(hoveredHex.isValid())
  724. {
  725. const CStack * const stack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  726. if (stack)
  727. return {stack};
  728. }
  729. return {};
  730. }