BattleAnimationClasses.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. /*
  2. * BattleAnimationClasses.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 "BattleAnimationClasses.h"
  12. #include "BattleInterface.h"
  13. #include "BattleInterfaceClasses.h"
  14. #include "BattleProjectileController.h"
  15. #include "BattleSiegeController.h"
  16. #include "BattleFieldController.h"
  17. #include "BattleEffectsController.h"
  18. #include "BattleStacksController.h"
  19. #include "CreatureAnimation.h"
  20. #include "../CGameInfo.h"
  21. #include "../CMusicHandler.h"
  22. #include "../CPlayerInterface.h"
  23. #include "../gui/CursorHandler.h"
  24. #include "../gui/CGuiHandler.h"
  25. #include "../../CCallback.h"
  26. #include "../../lib/CStack.h"
  27. BattleAnimation::BattleAnimation(BattleInterface & owner)
  28. : owner(owner),
  29. ID(owner.stacksController->animIDhelper++),
  30. initialized(false)
  31. {
  32. logAnim->trace("Animation #%d created", ID);
  33. }
  34. bool BattleAnimation::tryInitialize()
  35. {
  36. assert(!initialized);
  37. if ( init() )
  38. {
  39. initialized = true;
  40. return true;
  41. }
  42. return false;
  43. }
  44. bool BattleAnimation::isInitialized()
  45. {
  46. return initialized;
  47. }
  48. BattleAnimation::~BattleAnimation()
  49. {
  50. logAnim->trace("Animation #%d ended, type is %s", ID, typeid(this).name());
  51. for(auto & elem : pendingAnimations())
  52. {
  53. if(elem == this)
  54. elem = nullptr;
  55. }
  56. logAnim->trace("Animation #%d deleted", ID);
  57. }
  58. std::vector<BattleAnimation *> & BattleAnimation::pendingAnimations()
  59. {
  60. return owner.stacksController->currentAnimations;
  61. }
  62. std::shared_ptr<CreatureAnimation> BattleAnimation::stackAnimation(const CStack * stack) const
  63. {
  64. return owner.stacksController->stackAnimation[stack->ID];
  65. }
  66. bool BattleAnimation::stackFacingRight(const CStack * stack)
  67. {
  68. return owner.stacksController->stackFacingRight[stack->ID];
  69. }
  70. void BattleAnimation::setStackFacingRight(const CStack * stack, bool facingRight)
  71. {
  72. owner.stacksController->stackFacingRight[stack->ID] = facingRight;
  73. }
  74. BattleStackAnimation::BattleStackAnimation(BattleInterface & owner, const CStack * stack)
  75. : BattleAnimation(owner),
  76. myAnim(stackAnimation(stack)),
  77. stack(stack)
  78. {
  79. assert(myAnim);
  80. }
  81. StackActionAnimation::StackActionAnimation(BattleInterface & owner, const CStack * stack)
  82. : BattleStackAnimation(owner, stack)
  83. , nextGroup(ECreatureAnimType::HOLDING)
  84. , currGroup(ECreatureAnimType::HOLDING)
  85. {
  86. }
  87. ECreatureAnimType StackActionAnimation::getGroup() const
  88. {
  89. return currGroup;
  90. }
  91. void StackActionAnimation::setNextGroup( ECreatureAnimType group )
  92. {
  93. nextGroup = group;
  94. }
  95. void StackActionAnimation::setGroup( ECreatureAnimType group )
  96. {
  97. currGroup = group;
  98. }
  99. void StackActionAnimation::setSound( std::string sound )
  100. {
  101. this->sound = sound;
  102. }
  103. bool StackActionAnimation::init()
  104. {
  105. if (!sound.empty())
  106. CCS->soundh->playSound(sound);
  107. if (myAnim->framesInGroup(currGroup) > 0)
  108. {
  109. myAnim->playOnce(currGroup);
  110. myAnim->onAnimationReset += [&](){ delete this; };
  111. }
  112. else
  113. delete this;
  114. return true;
  115. }
  116. StackActionAnimation::~StackActionAnimation()
  117. {
  118. if (stack->isFrozen())
  119. myAnim->setType(ECreatureAnimType::HOLDING);
  120. else
  121. myAnim->setType(nextGroup);
  122. }
  123. ECreatureAnimType AttackAnimation::findValidGroup( const std::vector<ECreatureAnimType> candidates ) const
  124. {
  125. for ( auto group : candidates)
  126. {
  127. if(myAnim->framesInGroup(group) > 0)
  128. return group;
  129. }
  130. assert(0);
  131. return ECreatureAnimType::HOLDING;
  132. }
  133. const CCreature * AttackAnimation::getCreature() const
  134. {
  135. if (attackingStack->getCreature()->idNumber == CreatureID::ARROW_TOWERS)
  136. return owner.siegeController->getTurretCreature();
  137. else
  138. return attackingStack->getCreature();
  139. }
  140. AttackAnimation::AttackAnimation(BattleInterface & owner, const CStack *attacker, BattleHex _dest, const CStack *defender)
  141. : StackActionAnimation(owner, attacker),
  142. dest(_dest),
  143. defendingStack(defender),
  144. attackingStack(attacker)
  145. {
  146. assert(attackingStack && "attackingStack is nullptr in CBattleAttack::CBattleAttack !\n");
  147. attackingStackPosBeforeReturn = attackingStack->getPosition();
  148. }
  149. HittedAnimation::HittedAnimation(BattleInterface & owner, const CStack * stack)
  150. : StackActionAnimation(owner, stack)
  151. {
  152. setGroup(ECreatureAnimType::HITTED);
  153. setSound(battle_sound(stack->getCreature(), wince));
  154. logAnim->debug("Created HittedAnimation for %s", stack->getName());
  155. }
  156. DefenceAnimation::DefenceAnimation(BattleInterface & owner, const CStack * stack)
  157. : StackActionAnimation(owner, stack)
  158. {
  159. setGroup(ECreatureAnimType::DEFENCE);
  160. setSound(battle_sound(stack->getCreature(), defend));
  161. logAnim->debug("Created DefenceAnimation for %s", stack->getName());
  162. }
  163. DeathAnimation::DeathAnimation(BattleInterface & owner, const CStack * stack, bool ranged):
  164. StackActionAnimation(owner, stack)
  165. {
  166. setSound(battle_sound(stack->getCreature(), killed));
  167. if(ranged && myAnim->framesInGroup(ECreatureAnimType::DEATH_RANGED) > 0)
  168. setGroup(ECreatureAnimType::DEATH_RANGED);
  169. else
  170. setGroup(ECreatureAnimType::DEATH);
  171. if(ranged && myAnim->framesInGroup(ECreatureAnimType::DEAD_RANGED) > 0)
  172. setNextGroup(ECreatureAnimType::DEAD_RANGED);
  173. else
  174. setNextGroup(ECreatureAnimType::DEAD);
  175. logAnim->debug("Created DeathAnimation for %s", stack->getName());
  176. }
  177. DummyAnimation::DummyAnimation(BattleInterface & owner, int howManyFrames)
  178. : BattleAnimation(owner),
  179. counter(0),
  180. howMany(howManyFrames)
  181. {
  182. logAnim->debug("Created dummy animation for %d frames", howManyFrames);
  183. }
  184. bool DummyAnimation::init()
  185. {
  186. return true;
  187. }
  188. void DummyAnimation::nextFrame()
  189. {
  190. counter++;
  191. if(counter > howMany)
  192. delete this;
  193. }
  194. ECreatureAnimType MeleeAttackAnimation::getUpwardsGroup(bool multiAttack) const
  195. {
  196. if (!multiAttack)
  197. return ECreatureAnimType::ATTACK_UP;
  198. return findValidGroup({
  199. ECreatureAnimType::GROUP_ATTACK_UP,
  200. ECreatureAnimType::SPECIAL_UP,
  201. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  202. ECreatureAnimType::ATTACK_UP
  203. });
  204. }
  205. ECreatureAnimType MeleeAttackAnimation::getForwardGroup(bool multiAttack) const
  206. {
  207. if (!multiAttack)
  208. return ECreatureAnimType::ATTACK_FRONT;
  209. return findValidGroup({
  210. ECreatureAnimType::GROUP_ATTACK_FRONT,
  211. ECreatureAnimType::SPECIAL_FRONT,
  212. ECreatureAnimType::ATTACK_FRONT
  213. });
  214. }
  215. ECreatureAnimType MeleeAttackAnimation::getDownwardsGroup(bool multiAttack) const
  216. {
  217. if (!multiAttack)
  218. return ECreatureAnimType::ATTACK_DOWN;
  219. return findValidGroup({
  220. ECreatureAnimType::GROUP_ATTACK_DOWN,
  221. ECreatureAnimType::SPECIAL_DOWN,
  222. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  223. ECreatureAnimType::ATTACK_DOWN
  224. });
  225. }
  226. ECreatureAnimType MeleeAttackAnimation::selectGroup(bool multiAttack)
  227. {
  228. const ECreatureAnimType mutPosToGroup[] =
  229. {
  230. getUpwardsGroup (multiAttack),
  231. getUpwardsGroup (multiAttack),
  232. getForwardGroup (multiAttack),
  233. getDownwardsGroup(multiAttack),
  234. getDownwardsGroup(multiAttack),
  235. getForwardGroup (multiAttack)
  236. };
  237. int revShiftattacker = (attackingStack->side == BattleSide::ATTACKER ? -1 : 1);
  238. int mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, dest);
  239. if(mutPos == -1 && attackingStack->doubleWide())
  240. {
  241. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, defendingStack->getPosition());
  242. }
  243. if (mutPos == -1 && defendingStack->doubleWide())
  244. {
  245. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, defendingStack->occupiedHex());
  246. }
  247. if (mutPos == -1 && defendingStack->doubleWide() && attackingStack->doubleWide())
  248. {
  249. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, defendingStack->occupiedHex());
  250. }
  251. assert(mutPos >= 0 && mutPos <=5);
  252. return mutPosToGroup[mutPos];
  253. }
  254. void MeleeAttackAnimation::nextFrame()
  255. {
  256. size_t currentFrame = stackAnimation(attackingStack)->getCurrentFrame();
  257. size_t totalFrames = stackAnimation(attackingStack)->framesInGroup(getGroup());
  258. if ( currentFrame * 2 >= totalFrames )
  259. owner.executeAnimationStage(EAnimationEvents::HIT);
  260. AttackAnimation::nextFrame();
  261. }
  262. MeleeAttackAnimation::MeleeAttackAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, bool multiAttack)
  263. : AttackAnimation(owner, attacker, _dest, _attacked)
  264. {
  265. logAnim->debug("Created MeleeAttackAnimation for %s", attacker->getName());
  266. setSound(battle_sound(getCreature(), attack));
  267. setGroup(selectGroup(multiAttack));
  268. }
  269. StackMoveAnimation::StackMoveAnimation(BattleInterface & owner, const CStack * _stack, BattleHex prevHex, BattleHex nextHex):
  270. BattleStackAnimation(owner, _stack),
  271. prevHex(prevHex),
  272. nextHex(nextHex)
  273. {
  274. }
  275. bool MovementAnimation::init()
  276. {
  277. assert(stack);
  278. assert(!myAnim->isDeadOrDying());
  279. assert(stackAnimation(stack)->framesInGroup(ECreatureAnimType::MOVING) > 0);
  280. if(stackAnimation(stack)->framesInGroup(ECreatureAnimType::MOVING) == 0)
  281. {
  282. //no movement, end immediately
  283. delete this;
  284. return false;
  285. }
  286. logAnim->debug("CMovementAnimation::init: stack %s moves %d -> %d", stack->getName(), prevHex, nextHex);
  287. //reverse unit if necessary
  288. if(owner.stacksController->shouldRotate(stack, prevHex, nextHex))
  289. {
  290. // it seems that H3 does NOT plays full rotation animation during movement
  291. // Logical since it takes quite a lot of time
  292. rotateStack(prevHex);
  293. }
  294. if(myAnim->getType() != ECreatureAnimType::MOVING)
  295. {
  296. myAnim->setType(ECreatureAnimType::MOVING);
  297. }
  298. if (owner.moveSoundHander == -1)
  299. {
  300. owner.moveSoundHander = CCS->soundh->playSound(battle_sound(stack->getCreature(), move), -1);
  301. }
  302. Point begPosition = owner.stacksController->getStackPositionAtHex(prevHex, stack);
  303. Point endPosition = owner.stacksController->getStackPositionAtHex(nextHex, stack);
  304. progressPerSecond = AnimationControls::getMovementDistance(stack->getCreature());
  305. begX = begPosition.x;
  306. begY = begPosition.y;
  307. //progress = 0;
  308. distanceX = endPosition.x - begPosition.x;
  309. distanceY = endPosition.y - begPosition.y;
  310. if (stack->hasBonus(Selector::type()(Bonus::FLYING)))
  311. {
  312. float distance = static_cast<float>(sqrt(distanceX * distanceX + distanceY * distanceY));
  313. progressPerSecond = AnimationControls::getFlightDistance(stack->getCreature()) / distance;
  314. }
  315. return true;
  316. }
  317. void MovementAnimation::nextFrame()
  318. {
  319. progress += float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000 * progressPerSecond;
  320. //moving instructions
  321. myAnim->pos.x = static_cast<Sint16>(begX + distanceX * progress );
  322. myAnim->pos.y = static_cast<Sint16>(begY + distanceY * progress );
  323. BattleAnimation::nextFrame();
  324. if(progress >= 1.0)
  325. {
  326. progress -= 1.0;
  327. // Sets the position of the creature animation sprites
  328. Point coords = owner.stacksController->getStackPositionAtHex(nextHex, stack);
  329. myAnim->pos.moveTo(coords);
  330. // true if creature haven't reached the final destination hex
  331. if ((curentMoveIndex + 1) < destTiles.size())
  332. {
  333. // update the next hex field which has to be reached by the stack
  334. curentMoveIndex++;
  335. prevHex = nextHex;
  336. nextHex = destTiles[curentMoveIndex];
  337. // request re-initialization
  338. initialized = false;
  339. }
  340. else
  341. delete this;
  342. }
  343. }
  344. MovementAnimation::~MovementAnimation()
  345. {
  346. assert(stack);
  347. if(owner.moveSoundHander != -1)
  348. {
  349. CCS->soundh->stopSound(owner.moveSoundHander);
  350. owner.moveSoundHander = -1;
  351. }
  352. }
  353. MovementAnimation::MovementAnimation(BattleInterface & owner, const CStack *stack, std::vector<BattleHex> _destTiles, int _distance)
  354. : StackMoveAnimation(owner, stack, stack->getPosition(), _destTiles.front()),
  355. destTiles(_destTiles),
  356. curentMoveIndex(0),
  357. begX(0), begY(0),
  358. distanceX(0), distanceY(0),
  359. progressPerSecond(0.0),
  360. progress(0.0)
  361. {
  362. logAnim->debug("Created MovementAnimation for %s", stack->getName());
  363. }
  364. MovementEndAnimation::MovementEndAnimation(BattleInterface & owner, const CStack * _stack, BattleHex destTile)
  365. : StackMoveAnimation(owner, _stack, destTile, destTile)
  366. {
  367. logAnim->debug("Created MovementEndAnimation for %s", stack->getName());
  368. }
  369. bool MovementEndAnimation::init()
  370. {
  371. assert(stack);
  372. assert(!myAnim->isDeadOrDying());
  373. if(!stack || myAnim->isDeadOrDying())
  374. {
  375. delete this;
  376. return false;
  377. }
  378. logAnim->debug("CMovementEndAnimation::init: stack %s", stack->getName());
  379. myAnim->pos.moveTo(owner.stacksController->getStackPositionAtHex(nextHex, stack));
  380. CCS->soundh->playSound(battle_sound(stack->getCreature(), endMoving));
  381. if(!myAnim->framesInGroup(ECreatureAnimType::MOVE_END))
  382. {
  383. delete this;
  384. return false;
  385. }
  386. myAnim->setType(ECreatureAnimType::MOVE_END);
  387. myAnim->onAnimationReset += [&](){ delete this; };
  388. return true;
  389. }
  390. MovementEndAnimation::~MovementEndAnimation()
  391. {
  392. if(myAnim->getType() != ECreatureAnimType::DEAD)
  393. myAnim->setType(ECreatureAnimType::HOLDING); //resetting to default
  394. CCS->curh->show();
  395. }
  396. MovementStartAnimation::MovementStartAnimation(BattleInterface & owner, const CStack * _stack)
  397. : StackMoveAnimation(owner, _stack, _stack->getPosition(), _stack->getPosition())
  398. {
  399. logAnim->debug("Created MovementStartAnimation for %s", stack->getName());
  400. }
  401. bool MovementStartAnimation::init()
  402. {
  403. assert(stack);
  404. assert(!myAnim->isDeadOrDying());
  405. if(!stack || myAnim->isDeadOrDying())
  406. {
  407. delete this;
  408. return false;
  409. }
  410. logAnim->debug("CMovementStartAnimation::init: stack %s", stack->getName());
  411. CCS->soundh->playSound(battle_sound(stack->getCreature(), startMoving));
  412. if(!myAnim->framesInGroup(ECreatureAnimType::MOVE_START))
  413. {
  414. delete this;
  415. return false;
  416. }
  417. myAnim->setType(ECreatureAnimType::MOVE_START);
  418. myAnim->onAnimationReset += [&](){ delete this; };
  419. return true;
  420. }
  421. ReverseAnimation::ReverseAnimation(BattleInterface & owner, const CStack * stack, BattleHex dest)
  422. : StackMoveAnimation(owner, stack, dest, dest)
  423. {
  424. logAnim->debug("Created ReverseAnimation for %s", stack->getName());
  425. }
  426. bool ReverseAnimation::init()
  427. {
  428. assert(myAnim);
  429. assert(!myAnim->isDeadOrDying());
  430. if(myAnim == nullptr || myAnim->isDeadOrDying())
  431. {
  432. delete this;
  433. return false; //there is no such creature
  434. }
  435. logAnim->debug("CReverseAnimation::init: stack %s", stack->getName());
  436. if(myAnim->framesInGroup(ECreatureAnimType::TURN_L))
  437. {
  438. myAnim->playOnce(ECreatureAnimType::TURN_L);
  439. myAnim->onAnimationReset += std::bind(&ReverseAnimation::setupSecondPart, this);
  440. }
  441. else
  442. {
  443. setupSecondPart();
  444. }
  445. return true;
  446. }
  447. void BattleStackAnimation::rotateStack(BattleHex hex)
  448. {
  449. setStackFacingRight(stack, !stackFacingRight(stack));
  450. stackAnimation(stack)->pos.moveTo(owner.stacksController->getStackPositionAtHex(hex, stack));
  451. }
  452. void ReverseAnimation::setupSecondPart()
  453. {
  454. assert(stack);
  455. if(!stack)
  456. {
  457. delete this;
  458. return;
  459. }
  460. rotateStack(nextHex);
  461. if(myAnim->framesInGroup(ECreatureAnimType::TURN_R))
  462. {
  463. myAnim->playOnce(ECreatureAnimType::TURN_R);
  464. myAnim->onAnimationReset += [&](){ delete this; };
  465. }
  466. else
  467. delete this;
  468. }
  469. ResurrectionAnimation::ResurrectionAnimation(BattleInterface & owner, const CStack * _stack):
  470. StackActionAnimation(owner, _stack)
  471. {
  472. setGroup(ECreatureAnimType::RESURRECTION);
  473. logAnim->debug("Created ResurrectionAnimation for %s", stack->getName());
  474. }
  475. bool ColorTransformAnimation::init()
  476. {
  477. return true;
  478. }
  479. void ColorTransformAnimation::nextFrame()
  480. {
  481. float elapsed = GH.mainFPSmng->getElapsedMilliseconds() / 1000.f;
  482. float fullTime = AnimationControls::getFadeInDuration();
  483. float delta = elapsed / fullTime;
  484. totalProgress += delta;
  485. size_t index = 0;
  486. while (index < timePoints.size() && timePoints[index] < totalProgress )
  487. ++index;
  488. if (index == timePoints.size())
  489. {
  490. //end of animation. Apply ColorShifter using final values and die
  491. const auto & shifter = steps[index - 1];
  492. owner.stacksController->setStackColorFilter(shifter, stack, spell, false);
  493. delete this;
  494. return;
  495. }
  496. assert(index != 0);
  497. const auto & prevShifter = steps[index - 1];
  498. const auto & nextShifter = steps[index];
  499. float prevPoint = timePoints[index-1];
  500. float nextPoint = timePoints[index];
  501. float localProgress = totalProgress - prevPoint;
  502. float stepDuration = (nextPoint - prevPoint);
  503. float factor = localProgress / stepDuration;
  504. auto shifter = ColorFilter::genInterpolated(prevShifter, nextShifter, factor);
  505. owner.stacksController->setStackColorFilter(shifter, stack, spell, true);
  506. }
  507. ColorTransformAnimation::ColorTransformAnimation(BattleInterface & owner, const CStack * _stack, const std::string & colorFilterName, const CSpell * spell):
  508. BattleStackAnimation(owner, _stack),
  509. spell(spell),
  510. totalProgress(0.f)
  511. {
  512. auto effect = owner.effectsController->getMuxerEffect(colorFilterName);
  513. steps = effect.filters;
  514. timePoints = effect.timePoints;
  515. assert(!steps.empty() && steps.size() == timePoints.size());
  516. logAnim->debug("Created ColorTransformAnimation for %s", stack->getName());
  517. }
  518. RangedAttackAnimation::RangedAttackAnimation(BattleInterface & owner_, const CStack * attacker, BattleHex dest_, const CStack * defender)
  519. : AttackAnimation(owner_, attacker, dest_, defender),
  520. projectileEmitted(false)
  521. {
  522. setSound(battle_sound(getCreature(), shoot));
  523. }
  524. bool RangedAttackAnimation::init()
  525. {
  526. setAnimationGroup();
  527. initializeProjectile();
  528. return AttackAnimation::init();
  529. }
  530. void RangedAttackAnimation::setAnimationGroup()
  531. {
  532. Point shooterPos = stackAnimation(attackingStack)->pos.topLeft();
  533. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, defendingStack);
  534. //maximal angle in radians between straight horizontal line and shooting line for which shot is considered to be straight (absoulte value)
  535. static const double straightAngle = 0.2;
  536. double projectileAngle = -atan2(shotTarget.y - shooterPos.y, std::abs(shotTarget.x - shooterPos.x));
  537. // Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
  538. if (projectileAngle > straightAngle)
  539. setGroup(getUpwardsGroup());
  540. else if (projectileAngle < -straightAngle)
  541. setGroup(getDownwardsGroup());
  542. else
  543. setGroup(getForwardGroup());
  544. }
  545. void RangedAttackAnimation::initializeProjectile()
  546. {
  547. const CCreature *shooterInfo = getCreature();
  548. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, defendingStack) + Point(225, 225);
  549. Point shotOrigin = stackAnimation(attackingStack)->pos.topLeft() + Point(222, 265);
  550. int multiplier = stackFacingRight(attackingStack) ? 1 : -1;
  551. if (getGroup() == getUpwardsGroup())
  552. {
  553. shotOrigin.x += ( -25 + shooterInfo->animation.upperRightMissleOffsetX ) * multiplier;
  554. shotOrigin.y += shooterInfo->animation.upperRightMissleOffsetY;
  555. }
  556. else if (getGroup() == getDownwardsGroup())
  557. {
  558. shotOrigin.x += ( -25 + shooterInfo->animation.lowerRightMissleOffsetX ) * multiplier;
  559. shotOrigin.y += shooterInfo->animation.lowerRightMissleOffsetY;
  560. }
  561. else if (getGroup() == getForwardGroup())
  562. {
  563. shotOrigin.x += ( -25 + shooterInfo->animation.rightMissleOffsetX ) * multiplier;
  564. shotOrigin.y += shooterInfo->animation.rightMissleOffsetY;
  565. }
  566. else
  567. {
  568. assert(0);
  569. }
  570. createProjectile(shotOrigin, shotTarget);
  571. }
  572. void RangedAttackAnimation::emitProjectile()
  573. {
  574. logAnim->debug("Ranged attack projectile emitted");
  575. owner.projectilesController->emitStackProjectile(attackingStack);
  576. projectileEmitted = true;
  577. }
  578. void RangedAttackAnimation::nextFrame()
  579. {
  580. // animation should be paused if there is an active projectile
  581. if (projectileEmitted)
  582. {
  583. if (!owner.projectilesController->hasActiveProjectile(attackingStack, false))
  584. owner.executeAnimationStage(EAnimationEvents::HIT);
  585. }
  586. AttackAnimation::nextFrame();
  587. if (!projectileEmitted)
  588. {
  589. // emit projectile once animation playback reached "climax" frame
  590. if ( stackAnimation(attackingStack)->getCurrentFrame() >= getAttackClimaxFrame() )
  591. {
  592. emitProjectile();
  593. return;
  594. }
  595. }
  596. }
  597. RangedAttackAnimation::~RangedAttackAnimation()
  598. {
  599. assert(!owner.projectilesController->hasActiveProjectile(attackingStack, false));
  600. assert(projectileEmitted);
  601. // FIXME: is this possible? Animation is over but we're yet to fire projectile?
  602. if (!projectileEmitted)
  603. {
  604. logAnim->warn("Shooting animation has finished but projectile was not emitted! Emitting it now...");
  605. emitProjectile();
  606. }
  607. }
  608. ShootingAnimation::ShootingAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
  609. : RangedAttackAnimation(owner, attacker, _dest, _attacked)
  610. {
  611. logAnim->debug("Created ShootingAnimation for %s", stack->getName());
  612. }
  613. void ShootingAnimation::createProjectile(const Point & from, const Point & dest) const
  614. {
  615. owner.projectilesController->createProjectile(attackingStack, from, dest);
  616. }
  617. uint32_t ShootingAnimation::getAttackClimaxFrame() const
  618. {
  619. const CCreature *shooterInfo = getCreature();
  620. return shooterInfo->animation.attackClimaxFrame;
  621. }
  622. ECreatureAnimType ShootingAnimation::getUpwardsGroup() const
  623. {
  624. return ECreatureAnimType::SHOOT_UP;
  625. }
  626. ECreatureAnimType ShootingAnimation::getForwardGroup() const
  627. {
  628. return ECreatureAnimType::SHOOT_FRONT;
  629. }
  630. ECreatureAnimType ShootingAnimation::getDownwardsGroup() const
  631. {
  632. return ECreatureAnimType::SHOOT_DOWN;
  633. }
  634. CatapultAnimation::CatapultAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, int _catapultDmg)
  635. : ShootingAnimation(owner, attacker, _dest, _attacked),
  636. catapultDamage(_catapultDmg),
  637. explosionEmitted(false)
  638. {
  639. logAnim->debug("Created shooting anim for %s", stack->getName());
  640. }
  641. void CatapultAnimation::nextFrame()
  642. {
  643. ShootingAnimation::nextFrame();
  644. if ( explosionEmitted)
  645. return;
  646. if ( !projectileEmitted)
  647. return;
  648. if (owner.projectilesController->hasActiveProjectile(attackingStack, false))
  649. return;
  650. explosionEmitted = true;
  651. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, defendingStack) + Point(225, 225) - Point(126, 105);
  652. std::string soundFilename = (catapultDamage > 0) ? "WALLHIT" : "WALLMISS";
  653. std::string effectFilename = (catapultDamage > 0) ? "SGEXPL" : "CSGRCK";
  654. CCS->soundh->playSound( soundFilename );
  655. owner.stacksController->addNewAnim( new EffectAnimation(owner, effectFilename, shotTarget));
  656. }
  657. void CatapultAnimation::createProjectile(const Point & from, const Point & dest) const
  658. {
  659. owner.projectilesController->createCatapultProjectile(attackingStack, from, dest);
  660. }
  661. CastAnimation::CastAnimation(BattleInterface & owner_, const CStack * attacker, BattleHex dest, const CStack * defender, const CSpell * spell)
  662. : RangedAttackAnimation(owner_, attacker, dest, defender),
  663. spell(spell)
  664. {
  665. if(!dest.isValid())
  666. {
  667. assert(spell->animationInfo.projectile.empty());
  668. if (defender)
  669. dest = defender->getPosition();
  670. else
  671. dest = attacker->getPosition();
  672. }
  673. }
  674. ECreatureAnimType CastAnimation::getUpwardsGroup() const
  675. {
  676. return findValidGroup({
  677. ECreatureAnimType::CAST_UP,
  678. ECreatureAnimType::SPECIAL_UP,
  679. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  680. ECreatureAnimType::SHOOT_UP,
  681. ECreatureAnimType::ATTACK_UP
  682. });
  683. }
  684. ECreatureAnimType CastAnimation::getForwardGroup() const
  685. {
  686. return findValidGroup({
  687. ECreatureAnimType::CAST_FRONT,
  688. ECreatureAnimType::SPECIAL_FRONT,
  689. ECreatureAnimType::SHOOT_FRONT,
  690. ECreatureAnimType::ATTACK_FRONT
  691. });
  692. }
  693. ECreatureAnimType CastAnimation::getDownwardsGroup() const
  694. {
  695. return findValidGroup({
  696. ECreatureAnimType::CAST_DOWN,
  697. ECreatureAnimType::SPECIAL_DOWN,
  698. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  699. ECreatureAnimType::SHOOT_DOWN,
  700. ECreatureAnimType::ATTACK_DOWN
  701. });
  702. }
  703. void CastAnimation::createProjectile(const Point & from, const Point & dest) const
  704. {
  705. if (!spell->animationInfo.projectile.empty())
  706. owner.projectilesController->createSpellProjectile(attackingStack, from, dest, spell);
  707. }
  708. uint32_t CastAnimation::getAttackClimaxFrame() const
  709. {
  710. //TODO: allow defining this parameter in config file, separately from attackClimaxFrame of missile attacks
  711. uint32_t maxFrames = stackAnimation(attackingStack)->framesInGroup(getGroup());
  712. return maxFrames / 2;
  713. }
  714. EffectAnimation::EffectAnimation(BattleInterface & owner, std::string animationName, int effects):
  715. BattleAnimation(owner),
  716. animation(std::make_shared<CAnimation>(animationName)),
  717. effectFlags(effects),
  718. effectFinished(false)
  719. {
  720. logAnim->debug("CPointEffectAnimation::init: effect %s", animationName);
  721. }
  722. EffectAnimation::EffectAnimation(BattleInterface & owner, std::string animationName, std::vector<BattleHex> hex, int effects):
  723. EffectAnimation(owner, animationName, effects)
  724. {
  725. battlehexes = hex;
  726. }
  727. EffectAnimation::EffectAnimation(BattleInterface & owner, std::string animationName, BattleHex hex, int effects):
  728. EffectAnimation(owner, animationName, effects)
  729. {
  730. assert(hex.isValid());
  731. battlehexes.push_back(hex);
  732. }
  733. EffectAnimation::EffectAnimation(BattleInterface & owner, std::string animationName, std::vector<Point> pos, int effects):
  734. EffectAnimation(owner, animationName, effects)
  735. {
  736. positions = pos;
  737. }
  738. EffectAnimation::EffectAnimation(BattleInterface & owner, std::string animationName, Point pos, int effects):
  739. EffectAnimation(owner, animationName, effects)
  740. {
  741. positions.push_back(pos);
  742. }
  743. EffectAnimation::EffectAnimation(BattleInterface & owner, std::string animationName, Point pos, BattleHex hex, int effects):
  744. EffectAnimation(owner, animationName, effects)
  745. {
  746. assert(hex.isValid());
  747. battlehexes.push_back(hex);
  748. positions.push_back(pos);
  749. }
  750. bool EffectAnimation::init()
  751. {
  752. animation->preload();
  753. auto first = animation->getImage(0, 0, true);
  754. if(!first)
  755. {
  756. delete this;
  757. return false;
  758. }
  759. if (screenFill())
  760. {
  761. for(int i=0; i * first->width() < owner.fieldController->pos.w ; ++i)
  762. for(int j=0; j * first->height() < owner.fieldController->pos.h ; ++j)
  763. positions.push_back(Point( i * first->width(), j * first->height()));
  764. }
  765. BattleEffect be;
  766. be.effectID = ID;
  767. be.animation = animation;
  768. be.currentFrame = 0;
  769. for (size_t i = 0; i < std::max(battlehexes.size(), positions.size()); ++i)
  770. {
  771. bool hasTile = i < battlehexes.size();
  772. bool hasPosition = i < positions.size();
  773. if (hasTile && !forceOnTop())
  774. be.tile = battlehexes[i];
  775. else
  776. be.tile = BattleHex::INVALID;
  777. if (hasPosition)
  778. {
  779. be.pos.x = positions[i].x;
  780. be.pos.y = positions[i].y;
  781. }
  782. else
  783. {
  784. const CStack * destStack = owner.getCurrentPlayerInterface()->cb->battleGetStackByPos(battlehexes[i], false);
  785. Rect tilePos = owner.fieldController->hexPositionLocal(battlehexes[i]);
  786. be.pos.x = tilePos.x + tilePos.w/2 - first->width()/2;
  787. if(destStack && destStack->doubleWide()) // Correction for 2-hex creatures.
  788. be.pos.x += (destStack->side == BattleSide::ATTACKER ? -1 : 1)*tilePos.w/2;
  789. if (alignToBottom())
  790. be.pos.y = tilePos.y + tilePos.h - first->height();
  791. else
  792. be.pos.y = tilePos.y - first->height()/2;
  793. }
  794. owner.effectsController->battleEffects.push_back(be);
  795. }
  796. return true;
  797. }
  798. void EffectAnimation::nextFrame()
  799. {
  800. playEffect();
  801. if (effectFinished)
  802. {
  803. //remove visual effect itself only if sound has finished as well - necessary for obstacles like force field
  804. clearEffect();
  805. delete this;
  806. }
  807. }
  808. bool EffectAnimation::alignToBottom() const
  809. {
  810. return effectFlags & ALIGN_TO_BOTTOM;
  811. }
  812. bool EffectAnimation::forceOnTop() const
  813. {
  814. return effectFlags & FORCE_ON_TOP;
  815. }
  816. bool EffectAnimation::screenFill() const
  817. {
  818. return effectFlags & SCREEN_FILL;
  819. }
  820. void EffectAnimation::onEffectFinished()
  821. {
  822. effectFinished = true;
  823. }
  824. void EffectAnimation::playEffect()
  825. {
  826. if ( effectFinished )
  827. return;
  828. for(auto & elem : owner.effectsController->battleEffects)
  829. {
  830. if(elem.effectID == ID)
  831. {
  832. elem.currentFrame += AnimationControls::getSpellEffectSpeed() * GH.mainFPSmng->getElapsedMilliseconds() / 1000;
  833. if(elem.currentFrame >= elem.animation->size())
  834. {
  835. elem.currentFrame = elem.animation->size() - 1;
  836. onEffectFinished();
  837. break;
  838. }
  839. }
  840. }
  841. }
  842. void EffectAnimation::clearEffect()
  843. {
  844. auto & effects = owner.effectsController->battleEffects;
  845. vstd::erase_if(effects, [&](const BattleEffect & effect){
  846. return effect.effectID == ID;
  847. });
  848. }
  849. EffectAnimation::~EffectAnimation()
  850. {
  851. assert(effectFinished);
  852. }
  853. HeroCastAnimation::HeroCastAnimation(BattleInterface & owner, std::shared_ptr<BattleHero> hero, BattleHex dest, const CStack * defender, const CSpell * spell):
  854. BattleAnimation(owner),
  855. projectileEmitted(false),
  856. hero(hero),
  857. target(defender),
  858. tile(dest),
  859. spell(spell)
  860. {
  861. }
  862. bool HeroCastAnimation::init()
  863. {
  864. hero->setPhase(EHeroAnimType::CAST_SPELL);
  865. hero->onPhaseFinished([&](){
  866. delete this;
  867. });
  868. initializeProjectile();
  869. return true;
  870. }
  871. void HeroCastAnimation::initializeProjectile()
  872. {
  873. // spell has no projectile to play, ignore this step
  874. if (spell->animationInfo.projectile.empty())
  875. return;
  876. // targeted spells should have well, target
  877. assert(tile.isValid());
  878. Point srccoord = hero->pos.center() - hero->parent->pos.topLeft();
  879. Point destcoord = owner.stacksController->getStackPositionAtHex(tile, target); //position attacked by projectile
  880. destcoord += Point(222, 265); // FIXME: what are these constants?
  881. owner.projectilesController->createSpellProjectile( nullptr, srccoord, destcoord, spell);
  882. }
  883. void HeroCastAnimation::emitProjectile()
  884. {
  885. if (projectileEmitted)
  886. return;
  887. //spell has no projectile to play, skip this step and immediately play hit animations
  888. if (spell->animationInfo.projectile.empty())
  889. emitAnimationEvent();
  890. else
  891. owner.projectilesController->emitStackProjectile( nullptr );
  892. projectileEmitted = true;
  893. }
  894. void HeroCastAnimation::emitAnimationEvent()
  895. {
  896. owner.executeAnimationStage(EAnimationEvents::HIT);
  897. }
  898. void HeroCastAnimation::nextFrame()
  899. {
  900. float frame = hero->getFrame();
  901. if (frame < 4.0f) // middle point of animation //TODO: un-hardcode
  902. return;
  903. if (!projectileEmitted)
  904. {
  905. emitProjectile();
  906. hero->pause();
  907. return;
  908. }
  909. if (!owner.projectilesController->hasActiveProjectile(nullptr, false))
  910. {
  911. emitAnimationEvent();
  912. //TODO: check H3 - it is possible that hero animation should be paused until hit effect is over, not just projectile
  913. hero->play();
  914. }
  915. }