CBattleStacksController.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. /*
  2. * CBattleStacksController.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 "CBattleStacksController.h"
  12. #include "CBattleSiegeController.h"
  13. #include "CBattleInterfaceClasses.h"
  14. #include "CBattleInterface.h"
  15. #include "CBattleAnimations.h"
  16. #include "CBattleFieldController.h"
  17. #include "CBattleEffectsController.h"
  18. #include "CBattleProjectileController.h"
  19. #include "CBattleControlPanel.h"
  20. #include "../gui/CAnimation.h"
  21. #include "../gui/SDL_Extensions.h"
  22. #include "../gui/CGuiHandler.h"
  23. #include "../../lib/battle/BattleHex.h"
  24. #include "../CPlayerInterface.h"
  25. #include "CCreatureAnimation.h"
  26. #include "../../lib/CGameState.h"
  27. #include "../../CCallback.h"
  28. #include "../../lib/CStack.h"
  29. #include "../../lib/CondSh.h"
  30. #include "../CMusicHandler.h"
  31. #include "../CGameInfo.h"
  32. static void onAnimationFinished(const CStack *stack, std::weak_ptr<CCreatureAnimation> anim)
  33. {
  34. std::shared_ptr<CCreatureAnimation> animation = anim.lock();
  35. if(!animation)
  36. return;
  37. if (animation->isIdle())
  38. {
  39. const CCreature *creature = stack->getCreature();
  40. if (animation->framesInGroup(CCreatureAnim::MOUSEON) > 0)
  41. {
  42. if (CRandomGenerator::getDefault().nextDouble(99.0) < creature->animation.timeBetweenFidgets *10)
  43. animation->playOnce(CCreatureAnim::MOUSEON);
  44. else
  45. animation->setType(CCreatureAnim::HOLDING);
  46. }
  47. else
  48. {
  49. animation->setType(CCreatureAnim::HOLDING);
  50. }
  51. }
  52. // always reset callback
  53. animation->onAnimationReset += std::bind(&onAnimationFinished, stack, anim);
  54. }
  55. CBattleStacksController::CBattleStacksController(CBattleInterface * owner):
  56. owner(owner)
  57. {
  58. //preparing graphics for displaying amounts of creatures
  59. amountNormal = IImage::createFromFile("CMNUMWIN.BMP");
  60. amountPositive = IImage::createFromFile("CMNUMWIN.BMP");
  61. amountNegative = IImage::createFromFile("CMNUMWIN.BMP");
  62. amountEffNeutral = IImage::createFromFile("CMNUMWIN.BMP");
  63. ColorShifterAddMulExcept shifterNormal ({0,0,0,0}, {150, 48, 237, 255}, {132, 231, 255, 255});
  64. ColorShifterAddMulExcept shifterPositive({0,0,0,0}, { 45, 255, 45, 255}, {132, 231, 255, 255});
  65. ColorShifterAddMulExcept shifterNegative({0,0,0,0}, {255, 45, 45, 255}, {132, 231, 255, 255});
  66. ColorShifterAddMulExcept shifterNeutral ({0,0,0,0}, {255, 255, 45, 255}, {132, 231, 255, 255});
  67. amountNormal->adjustPalette(&shifterNormal);
  68. amountPositive->adjustPalette(&shifterPositive);
  69. amountNegative->adjustPalette(&shifterNegative);
  70. amountEffNeutral->adjustPalette(&shifterNeutral);
  71. std::vector<const CStack*> stacks = owner->curInt->cb->battleGetAllStacks(true);
  72. for(const CStack * s : stacks)
  73. {
  74. stackAdded(s);
  75. }
  76. }
  77. void CBattleStacksController::showBattlefieldObjects(SDL_Surface *to, const BattleHex & location )
  78. {
  79. auto getCurrentPosition = [&](const CStack *stack) -> BattleHex
  80. {
  81. for (auto & anim : pendingAnims)
  82. {
  83. // certainly ugly workaround but fixes quite annoying bug
  84. // stack position will be updated only *after* movement is finished
  85. // before this - stack is always at its initial position. Thus we need to find
  86. // its current position. Which can be found only in this class
  87. if (CMovementAnimation *move = dynamic_cast<CMovementAnimation*>(anim.first))
  88. {
  89. if (move->stack == stack)
  90. return move->nextHex;
  91. }
  92. }
  93. return stack->getPosition();
  94. };
  95. auto stacks = owner->curInt->cb->battleGetAllStacks(true);
  96. for (auto & stack : stacks)
  97. {
  98. if (creAnims.find(stack->ID) == creAnims.end()) //e.g. for summoned but not yet handled stacks
  99. continue;
  100. //if (stack->initialPosition < 0) // turret shooters are handled separately
  101. // continue;
  102. //FIXME: hack to ignore ghost stacks
  103. if ((creAnims[stack->ID]->getType() == CCreatureAnim::DEAD || creAnims[stack->ID]->getType() == CCreatureAnim::HOLDING) && stack->isGhost())
  104. continue;//ignore
  105. if (creAnims[stack->ID]->isDead())
  106. {
  107. //if ( location == stack->getPosition() )
  108. if ( location == BattleHex::HEX_BEFORE_ALL ) //FIXME: any cases when this won't work?
  109. {};
  110. continue;
  111. }
  112. // standing - blit at current position
  113. if (!creAnims[stack->ID]->isMoving())
  114. {
  115. if ( location == stack->getPosition() )
  116. {};
  117. continue;
  118. }
  119. // flying creature - just blit them over everyone else
  120. if (stack->hasBonusOfType(Bonus::FLYING))
  121. {
  122. if ( location == BattleHex::HEX_AFTER_ALL)
  123. {};
  124. continue;
  125. }
  126. // else - unit moving on ground
  127. {
  128. if ( location == getCurrentPosition(stack) )
  129. {};
  130. continue;
  131. }
  132. }
  133. }
  134. void CBattleStacksController::stackReset(const CStack * stack)
  135. {
  136. auto iter = creAnims.find(stack->ID);
  137. if(iter == creAnims.end())
  138. {
  139. logGlobal->error("Unit %d have no animation", stack->ID);
  140. return;
  141. }
  142. auto animation = iter->second;
  143. if(stack->alive() && animation->isDead())
  144. animation->setType(CCreatureAnim::HOLDING);
  145. if (stack->isClone())
  146. {
  147. auto shifter = ColorShifterAddMul::deepBlue();
  148. animation->shiftColor(&shifter);
  149. }
  150. //TODO: handle more cases
  151. }
  152. void CBattleStacksController::stackAdded(const CStack * stack)
  153. {
  154. creDir[stack->ID] = stack->side == BattleSide::ATTACKER; // must be set before getting stack position
  155. Point coords = CClickableHex::getXYUnitAnim(stack->getPosition(), stack, owner);
  156. if(stack->initialPosition < 0) //turret
  157. {
  158. assert(owner->siegeController);
  159. const CCreature *turretCreature = owner->siegeController->getTurretCreature();
  160. creAnims[stack->ID] = AnimationControls::getAnimation(turretCreature);
  161. creAnims[stack->ID]->pos.h = 225;
  162. coords = owner->siegeController->getTurretCreaturePosition(stack->initialPosition);
  163. }
  164. else
  165. {
  166. creAnims[stack->ID] = AnimationControls::getAnimation(stack->getCreature());
  167. creAnims[stack->ID]->onAnimationReset += std::bind(&onAnimationFinished, stack, creAnims[stack->ID]);
  168. creAnims[stack->ID]->pos.h = creAnims[stack->ID]->getHeight();
  169. }
  170. creAnims[stack->ID]->pos.x = coords.x;
  171. creAnims[stack->ID]->pos.y = coords.y;
  172. creAnims[stack->ID]->pos.w = creAnims[stack->ID]->getWidth();
  173. creAnims[stack->ID]->setType(CCreatureAnim::HOLDING);
  174. //loading projectiles for units
  175. if(stack->isShooter())
  176. {
  177. owner->projectilesController->initStackProjectile(stack);
  178. }
  179. }
  180. void CBattleStacksController::setActiveStack(const CStack *stack)
  181. {
  182. if (activeStack) // update UI
  183. creAnims[activeStack->ID]->setBorderColor(AnimationControls::getNoBorder());
  184. activeStack = stack;
  185. if (activeStack) // update UI
  186. creAnims[activeStack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  187. owner->controlPanel->blockUI(activeStack == nullptr);
  188. }
  189. void CBattleStacksController::setHoveredStack(const CStack *stack)
  190. {
  191. if ( stack == mouseHoveredStack )
  192. return;
  193. if (mouseHoveredStack)
  194. creAnims[mouseHoveredStack->ID]->setBorderColor(AnimationControls::getNoBorder());
  195. // stack must be alive and not active (which uses gold border instead)
  196. if (stack && stack->alive() && stack != activeStack)
  197. {
  198. mouseHoveredStack = stack;
  199. if (mouseHoveredStack)
  200. {
  201. creAnims[mouseHoveredStack->ID]->setBorderColor(AnimationControls::getBlueBorder());
  202. if (creAnims[mouseHoveredStack->ID]->framesInGroup(CCreatureAnim::MOUSEON) > 0)
  203. creAnims[mouseHoveredStack->ID]->playOnce(CCreatureAnim::MOUSEON);
  204. }
  205. }
  206. else
  207. mouseHoveredStack = nullptr;
  208. }
  209. bool CBattleStacksController::stackNeedsAmountBox(const CStack * stack)
  210. {
  211. BattleHex currentActionTarget;
  212. if(owner->curInt->curAction)
  213. {
  214. auto target = owner->curInt->curAction->getTarget(owner->curInt->cb.get());
  215. if(!target.empty())
  216. currentActionTarget = target.at(0).hexValue;
  217. }
  218. if(!stack->alive())
  219. return false;
  220. 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
  221. return false;
  222. if(stack->getCount() == 0) //hide box when target is going to die anyway - do not display "0 creatures"
  223. return false;
  224. for(auto anim : pendingAnims) //no matter what other conditions below are, hide box when creature is playing hit animation
  225. {
  226. auto hitAnimation = dynamic_cast<CDefenceAnimation*>(anim.first);
  227. if(hitAnimation && (hitAnimation->stack->ID == stack->ID)) //we process only "current creature" as other creatures will be processed reliably on their own iteration
  228. return false;
  229. }
  230. if(owner->curInt->curAction)
  231. {
  232. if(owner->curInt->curAction->stackNumber == stack->ID) //stack is currently taking action (is not a target of another creature's action etc)
  233. {
  234. if(owner->curInt->curAction->actionType == EActionType::WALK || owner->curInt->curAction->actionType == EActionType::SHOOT) //hide when stack walks or shoots
  235. return false;
  236. else if(owner->curInt->curAction->actionType == EActionType::WALK_AND_ATTACK && currentActionTarget != stack->getPosition()) //when attacking, hide until walk phase finished
  237. return false;
  238. }
  239. if(owner->curInt->curAction->actionType == EActionType::SHOOT && currentActionTarget == stack->getPosition()) //hide if we are ranged attack target
  240. return false;
  241. }
  242. return true;
  243. }
  244. void CBattleStacksController::showStackAmountBox(SDL_Surface *to, const CStack * stack)
  245. {
  246. auto getEffectsPositivness = [&](const std::vector<si32> & activeSpells) -> int
  247. {
  248. int pos = 0;
  249. for (const auto & spellId : activeSpells)
  250. {
  251. pos += CGI->spellh->objects.at(spellId)->positiveness;
  252. }
  253. return pos;
  254. };
  255. auto getAmountBoxBackground = [&](int positivness) -> auto
  256. {
  257. if (positivness > 0)
  258. return amountPositive;
  259. if (positivness < 0)
  260. return amountNegative;
  261. return amountEffNeutral;
  262. };
  263. const int sideShift = stack->side == BattleSide::ATTACKER ? 1 : -1;
  264. const int reverseSideShift = stack->side == BattleSide::ATTACKER ? -1 : 1;
  265. const BattleHex nextPos = stack->getPosition() + sideShift;
  266. const bool edge = stack->getPosition() % GameConstants::BFIELD_WIDTH == (stack->side == BattleSide::ATTACKER ? GameConstants::BFIELD_WIDTH - 2 : 1);
  267. const bool moveInside = !edge && !owner->fieldController->stackCountOutsideHex(nextPos);
  268. int xAdd = (stack->side == BattleSide::ATTACKER ? 220 : 202) +
  269. (stack->doubleWide() ? 44 : 0) * sideShift +
  270. (moveInside ? amountNormal->width() + 10 : 0) * reverseSideShift;
  271. int yAdd = 260 + ((stack->side == BattleSide::ATTACKER || moveInside) ? 0 : -15);
  272. //blitting amount background box
  273. std::vector<si32> activeSpells = stack->activeSpells();
  274. auto amountBG = activeSpells.empty() ? amountNormal : getAmountBoxBackground(getEffectsPositivness(activeSpells));
  275. amountBG->draw(to, creAnims[stack->ID]->pos.x + xAdd, creAnims[stack->ID]->pos.y + yAdd);
  276. //blitting amount
  277. Point textPos(creAnims[stack->ID]->pos.x + xAdd + amountNormal->width()/2,
  278. creAnims[stack->ID]->pos.y + yAdd + amountNormal->height()/2);
  279. graphics->fonts[FONT_TINY]->renderTextCenter(to, makeNumberShort(stack->getCount()), Colors::WHITE, textPos);
  280. }
  281. void CBattleStacksController::showStack(SDL_Surface *to, const CStack * stack)
  282. {
  283. creAnims[stack->ID]->nextFrame(to, facingRight(stack)); // do actual blit
  284. creAnims[stack->ID]->incrementFrame(float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000);
  285. if (stackNeedsAmountBox(stack))
  286. showStackAmountBox(to, stack);
  287. }
  288. void CBattleStacksController::updateBattleAnimations()
  289. {
  290. //handle animations
  291. for (auto & elem : pendingAnims)
  292. {
  293. if (!elem.first) //this animation should be deleted
  294. continue;
  295. if (!elem.second)
  296. {
  297. elem.second = elem.first->init();
  298. }
  299. if (elem.second && elem.first)
  300. elem.first->nextFrame();
  301. }
  302. //delete anims
  303. int preSize = static_cast<int>(pendingAnims.size());
  304. for (auto it = pendingAnims.begin(); it != pendingAnims.end(); ++it)
  305. {
  306. if (it->first == nullptr)
  307. {
  308. pendingAnims.erase(it);
  309. it = pendingAnims.begin();
  310. break;
  311. }
  312. }
  313. if (preSize > 0 && pendingAnims.empty())
  314. {
  315. //anims ended
  316. owner->controlPanel->blockUI(activeStack == nullptr);
  317. owner->animsAreDisplayed.setn(false);
  318. }
  319. }
  320. void CBattleStacksController::addNewAnim(CBattleAnimation *anim)
  321. {
  322. pendingAnims.push_back( std::make_pair(anim, false) );
  323. owner->animsAreDisplayed.setn(true);
  324. }
  325. void CBattleStacksController::stackActivated(const CStack *stack) //TODO: check it all before game state is changed due to abilities
  326. {
  327. stackToActivate = stack;
  328. owner->waitForAnims();
  329. if (stackToActivate) //during waiting stack may have gotten activated through show
  330. activateStack();
  331. }
  332. void CBattleStacksController::stackRemoved(uint32_t stackID)
  333. {
  334. if (getActiveStack() != nullptr)
  335. {
  336. if (getActiveStack()->ID == stackID)
  337. {
  338. BattleAction *action = new BattleAction();
  339. action->side = owner->defendingHeroInstance ? (owner->curInt->playerID == owner->defendingHeroInstance->tempOwner) : false;
  340. action->actionType = EActionType::CANCEL;
  341. action->stackNumber = owner->stacksController->getActiveStack()->ID;
  342. owner->givenCommand.setn(action);
  343. setActiveStack(nullptr);
  344. }
  345. }
  346. //todo: ensure that ghost stack animation has fadeout effect
  347. }
  348. void CBattleStacksController::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  349. {
  350. for(auto & attackedInfo : attackedInfos)
  351. {
  352. //if (!attackedInfo.cloneKilled) //FIXME: play dead animation for cloned creature before it vanishes
  353. addNewAnim(new CDefenceAnimation(attackedInfo, owner));
  354. if(attackedInfo.rebirth)
  355. {
  356. owner->effectsController->displayEffect(EBattleEffect::RESURRECT, soundBase::RESURECT, attackedInfo.defender->getPosition()); //TODO: play reverse death animation
  357. }
  358. }
  359. owner->waitForAnims();
  360. for (auto & attackedInfo : attackedInfos)
  361. {
  362. if (attackedInfo.rebirth)
  363. creAnims[attackedInfo.defender->ID]->setType(CCreatureAnim::HOLDING);
  364. if (attackedInfo.cloneKilled)
  365. stackRemoved(attackedInfo.defender->ID);
  366. }
  367. }
  368. void CBattleStacksController::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  369. {
  370. addNewAnim(new CMovementAnimation(owner, stack, destHex, distance));
  371. owner->waitForAnims();
  372. }
  373. void CBattleStacksController::stackAttacking( const CStack *attacker, BattleHex dest, const CStack *attacked, bool shooting )
  374. {
  375. if (shooting)
  376. {
  377. addNewAnim(new CShootingAnimation(owner, attacker, dest, attacked));
  378. }
  379. else
  380. {
  381. addNewAnim(new CMeleeAttackAnimation(owner, attacker, dest, attacked));
  382. }
  383. //waitForAnims();
  384. }
  385. bool CBattleStacksController::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex)
  386. {
  387. Point begPosition = CClickableHex::getXYUnitAnim(oldPos,stack, owner);
  388. Point endPosition = CClickableHex::getXYUnitAnim(nextHex, stack, owner);
  389. if((begPosition.x > endPosition.x) && facingRight(stack))
  390. return true;
  391. else if((begPosition.x < endPosition.x) && !facingRight(stack))
  392. return true;
  393. return false;
  394. }
  395. void CBattleStacksController::endAction(const BattleAction* action)
  396. {
  397. //check if we should reverse stacks
  398. //for some strange reason, it's not enough
  399. TStacks stacks = owner->curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
  400. for (const CStack *s : stacks)
  401. {
  402. bool shouldFaceRight = s && s->side == BattleSide::ATTACKER;
  403. if (s && facingRight(s) != shouldFaceRight && s->alive() && creAnims[s->ID]->isIdle())
  404. {
  405. addNewAnim(new CReverseAnimation(owner, s, s->getPosition(), false));
  406. }
  407. }
  408. }
  409. void CBattleStacksController::startAction(const BattleAction* action)
  410. {
  411. const CStack *stack = owner->curInt->cb->battleGetStackByID(action->stackNumber);
  412. setHoveredStack(nullptr);
  413. auto actionTarget = action->getTarget(owner->curInt->cb.get());
  414. if(action->actionType == EActionType::WALK
  415. || (action->actionType == EActionType::WALK_AND_ATTACK && actionTarget.at(0).hexValue != stack->getPosition()))
  416. {
  417. assert(stack);
  418. owner->moveStarted = true;
  419. if (creAnims[action->stackNumber]->framesInGroup(CCreatureAnim::MOVE_START))
  420. {
  421. pendingAnims.push_back(std::make_pair(new CMovementStartAnimation(owner, stack), false));
  422. }
  423. if(shouldRotate(stack, stack->getPosition(), actionTarget.at(0).hexValue))
  424. pendingAnims.push_back(std::make_pair(new CReverseAnimation(owner, stack, stack->getPosition(), true), false));
  425. }
  426. }
  427. void CBattleStacksController::activateStack()
  428. {
  429. if ( !pendingAnims.empty())
  430. return;
  431. if ( !stackToActivate)
  432. return;
  433. owner->trySetActivePlayer(stackToActivate->owner);
  434. setActiveStack(stackToActivate);
  435. stackToActivate = nullptr;
  436. const CStack * s = owner->stacksController->getActiveStack();
  437. if(!s)
  438. return;
  439. //set casting flag to true if creature can use it to not check it every time
  440. const auto spellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::SPELLCASTER));
  441. const auto randomSpellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::RANDOM_SPELLCASTER));
  442. if(s->canCast() && (spellcaster || randomSpellcaster))
  443. {
  444. stackCanCastSpell = true;
  445. if(randomSpellcaster)
  446. creatureSpellToCast = -1; //spell will be set later on cast
  447. else
  448. creatureSpellToCast = owner->curInt->cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), s, CBattleInfoCallback::RANDOM_AIMED); //faerie dragon can cast only one spell until their next move
  449. //TODO: what if creature can cast BOTH random genie spell and aimed spell?
  450. //TODO: faerie dragon type spell should be selected by server
  451. }
  452. else
  453. {
  454. stackCanCastSpell = false;
  455. creatureSpellToCast = -1;
  456. }
  457. }
  458. void CBattleStacksController::setSelectedStack(const CStack *stack)
  459. {
  460. selectedStack = stack;
  461. }
  462. const CStack* CBattleStacksController::getSelectedStack()
  463. {
  464. return selectedStack;
  465. }
  466. const CStack* CBattleStacksController::getActiveStack()
  467. {
  468. return activeStack;
  469. }
  470. bool CBattleStacksController::facingRight(const CStack * stack)
  471. {
  472. return creDir[stack->ID];
  473. }
  474. bool CBattleStacksController::activeStackSpellcaster()
  475. {
  476. return stackCanCastSpell;
  477. }
  478. SpellID CBattleStacksController::activeStackSpellToCast()
  479. {
  480. if (!stackCanCastSpell)
  481. return SpellID::NONE;
  482. return SpellID(creatureSpellToCast);
  483. }