BattleAnimationClasses.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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 "../CPlayerInterface.h"
  22. #include "../gui/CursorHandler.h"
  23. #include "../gui/CGuiHandler.h"
  24. #include "../media/ISoundPlayer.h"
  25. #include "../render/CAnimation.h"
  26. #include "../render/IRenderHandler.h"
  27. #include "../../CCallback.h"
  28. #include "../../lib/CStack.h"
  29. BattleAnimation::BattleAnimation(BattleInterface & owner)
  30. : owner(owner),
  31. ID(owner.stacksController->animIDhelper++),
  32. initialized(false)
  33. {
  34. logAnim->trace("Animation #%d created", ID);
  35. }
  36. bool BattleAnimation::tryInitialize()
  37. {
  38. assert(!initialized);
  39. if ( init() )
  40. {
  41. initialized = true;
  42. return true;
  43. }
  44. return false;
  45. }
  46. bool BattleAnimation::isInitialized()
  47. {
  48. return initialized;
  49. }
  50. BattleAnimation::~BattleAnimation()
  51. {
  52. logAnim->trace("Animation #%d ended, type is %s", ID, typeid(this).name());
  53. for(auto & elem : pendingAnimations())
  54. {
  55. if(elem == this)
  56. elem = nullptr;
  57. }
  58. logAnim->trace("Animation #%d deleted", ID);
  59. }
  60. std::vector<BattleAnimation *> & BattleAnimation::pendingAnimations()
  61. {
  62. return owner.stacksController->currentAnimations;
  63. }
  64. std::shared_ptr<CreatureAnimation> BattleAnimation::stackAnimation(const CStack * stack) const
  65. {
  66. return owner.stacksController->stackAnimation[stack->unitId()];
  67. }
  68. bool BattleAnimation::stackFacingRight(const CStack * stack)
  69. {
  70. return owner.stacksController->stackFacingRight[stack->unitId()];
  71. }
  72. void BattleAnimation::setStackFacingRight(const CStack * stack, bool facingRight)
  73. {
  74. owner.stacksController->stackFacingRight[stack->unitId()] = facingRight;
  75. }
  76. BattleStackAnimation::BattleStackAnimation(BattleInterface & owner, const CStack * stack)
  77. : BattleAnimation(owner),
  78. myAnim(stackAnimation(stack)),
  79. stack(stack)
  80. {
  81. assert(myAnim);
  82. }
  83. StackActionAnimation::StackActionAnimation(BattleInterface & owner, const CStack * stack)
  84. : BattleStackAnimation(owner, stack)
  85. , nextGroup(ECreatureAnimType::HOLDING)
  86. , currGroup(ECreatureAnimType::HOLDING)
  87. {
  88. }
  89. ECreatureAnimType StackActionAnimation::getGroup() const
  90. {
  91. return currGroup;
  92. }
  93. void StackActionAnimation::setNextGroup( ECreatureAnimType group )
  94. {
  95. nextGroup = group;
  96. }
  97. void StackActionAnimation::setGroup( ECreatureAnimType group )
  98. {
  99. currGroup = group;
  100. }
  101. void StackActionAnimation::setSound( const AudioPath & sound )
  102. {
  103. this->sound = sound;
  104. }
  105. bool StackActionAnimation::init()
  106. {
  107. if (!sound.empty())
  108. CCS->soundh->playSound(sound);
  109. if (myAnim->framesInGroup(currGroup) > 0)
  110. {
  111. myAnim->playOnce(currGroup);
  112. myAnim->onAnimationReset += [&](){ delete this; };
  113. }
  114. else
  115. delete this;
  116. return true;
  117. }
  118. StackActionAnimation::~StackActionAnimation()
  119. {
  120. if (stack->isFrozen() && currGroup != ECreatureAnimType::DEATH && currGroup != ECreatureAnimType::DEATH_RANGED)
  121. myAnim->setType(ECreatureAnimType::HOLDING);
  122. else
  123. myAnim->setType(nextGroup);
  124. }
  125. ECreatureAnimType AttackAnimation::findValidGroup( const std::vector<ECreatureAnimType> candidates ) const
  126. {
  127. for ( auto group : candidates)
  128. {
  129. if(myAnim->framesInGroup(group) > 0)
  130. return group;
  131. }
  132. assert(0);
  133. return ECreatureAnimType::HOLDING;
  134. }
  135. const CCreature * AttackAnimation::getCreature() const
  136. {
  137. if (attackingStack->unitType()->getId() == CreatureID::ARROW_TOWERS)
  138. return owner.siegeController->getTurretCreature(attackingStack->initialPosition);
  139. else
  140. return attackingStack->unitType();
  141. }
  142. AttackAnimation::AttackAnimation(BattleInterface & owner, const CStack *attacker, BattleHex _dest, const CStack *defender)
  143. : StackActionAnimation(owner, attacker),
  144. dest(_dest),
  145. defendingStack(defender),
  146. attackingStack(attacker)
  147. {
  148. assert(attackingStack && "attackingStack is nullptr in CBattleAttack::CBattleAttack !\n");
  149. attackingStackPosBeforeReturn = attackingStack->getPosition().toInt();
  150. }
  151. HittedAnimation::HittedAnimation(BattleInterface & owner, const CStack * stack)
  152. : StackActionAnimation(owner, stack)
  153. {
  154. setGroup(ECreatureAnimType::HITTED);
  155. setSound(stack->unitType()->sounds.wince);
  156. logAnim->debug("Created HittedAnimation for %s", stack->getName());
  157. }
  158. DefenceAnimation::DefenceAnimation(BattleInterface & owner, const CStack * stack)
  159. : StackActionAnimation(owner, stack)
  160. {
  161. setGroup(ECreatureAnimType::DEFENCE);
  162. setSound(stack->unitType()->sounds.defend);
  163. logAnim->debug("Created DefenceAnimation for %s", stack->getName());
  164. }
  165. DeathAnimation::DeathAnimation(BattleInterface & owner, const CStack * stack, bool ranged):
  166. StackActionAnimation(owner, stack)
  167. {
  168. setSound(stack->unitType()->sounds.killed);
  169. if(ranged && myAnim->framesInGroup(ECreatureAnimType::DEATH_RANGED) > 0)
  170. setGroup(ECreatureAnimType::DEATH_RANGED);
  171. else
  172. setGroup(ECreatureAnimType::DEATH);
  173. if(ranged && myAnim->framesInGroup(ECreatureAnimType::DEAD_RANGED) > 0)
  174. setNextGroup(ECreatureAnimType::DEAD_RANGED);
  175. else
  176. setNextGroup(ECreatureAnimType::DEAD);
  177. logAnim->debug("Created DeathAnimation for %s", stack->getName());
  178. }
  179. DummyAnimation::DummyAnimation(BattleInterface & owner, int howManyFrames)
  180. : BattleAnimation(owner),
  181. counter(0),
  182. howMany(howManyFrames)
  183. {
  184. logAnim->debug("Created dummy animation for %d frames", howManyFrames);
  185. }
  186. bool DummyAnimation::init()
  187. {
  188. return true;
  189. }
  190. void DummyAnimation::tick(uint32_t msPassed)
  191. {
  192. counter++;
  193. if(counter > howMany)
  194. delete this;
  195. }
  196. ECreatureAnimType MeleeAttackAnimation::getUpwardsGroup(bool multiAttack) const
  197. {
  198. if (!multiAttack)
  199. return ECreatureAnimType::ATTACK_UP;
  200. return findValidGroup({
  201. ECreatureAnimType::GROUP_ATTACK_UP,
  202. ECreatureAnimType::SPECIAL_UP,
  203. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  204. ECreatureAnimType::ATTACK_UP
  205. });
  206. }
  207. ECreatureAnimType MeleeAttackAnimation::getForwardGroup(bool multiAttack) const
  208. {
  209. if (!multiAttack)
  210. return ECreatureAnimType::ATTACK_FRONT;
  211. return findValidGroup({
  212. ECreatureAnimType::GROUP_ATTACK_FRONT,
  213. ECreatureAnimType::SPECIAL_FRONT,
  214. ECreatureAnimType::ATTACK_FRONT
  215. });
  216. }
  217. ECreatureAnimType MeleeAttackAnimation::getDownwardsGroup(bool multiAttack) const
  218. {
  219. if (!multiAttack)
  220. return ECreatureAnimType::ATTACK_DOWN;
  221. return findValidGroup({
  222. ECreatureAnimType::GROUP_ATTACK_DOWN,
  223. ECreatureAnimType::SPECIAL_DOWN,
  224. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  225. ECreatureAnimType::ATTACK_DOWN
  226. });
  227. }
  228. ECreatureAnimType MeleeAttackAnimation::selectGroup(bool multiAttack)
  229. {
  230. const ECreatureAnimType mutPosToGroup[] =
  231. {
  232. getUpwardsGroup (multiAttack),
  233. getUpwardsGroup (multiAttack),
  234. getForwardGroup (multiAttack),
  235. getDownwardsGroup(multiAttack),
  236. getDownwardsGroup(multiAttack),
  237. getForwardGroup (multiAttack)
  238. };
  239. int revShiftattacker = (attackingStack->unitSide() == BattleSide::ATTACKER ? -1 : 1);
  240. int mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, dest);
  241. if(mutPos == -1 && attackingStack->doubleWide())
  242. {
  243. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, defendingStack->getPosition());
  244. }
  245. if (mutPos == -1 && defendingStack->doubleWide())
  246. {
  247. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, defendingStack->occupiedHex());
  248. }
  249. if (mutPos == -1 && defendingStack->doubleWide() && attackingStack->doubleWide())
  250. {
  251. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, defendingStack->occupiedHex());
  252. }
  253. assert(mutPos >= 0 && mutPos <=5);
  254. return mutPosToGroup[mutPos];
  255. }
  256. void MeleeAttackAnimation::tick(uint32_t msPassed)
  257. {
  258. size_t currentFrame = stackAnimation(attackingStack)->getCurrentFrame();
  259. size_t totalFrames = stackAnimation(attackingStack)->framesInGroup(getGroup());
  260. if ( currentFrame * 2 >= totalFrames )
  261. owner.executeAnimationStage(EAnimationEvents::HIT);
  262. AttackAnimation::tick(msPassed);
  263. }
  264. MeleeAttackAnimation::MeleeAttackAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, bool multiAttack)
  265. : AttackAnimation(owner, attacker, _dest, _attacked)
  266. {
  267. logAnim->debug("Created MeleeAttackAnimation for %s", attacker->getName());
  268. setSound(getCreature()->sounds.attack);
  269. setGroup(selectGroup(multiAttack));
  270. }
  271. StackMoveAnimation::StackMoveAnimation(BattleInterface & owner, const CStack * _stack, BattleHex prevHex, BattleHex nextHex):
  272. BattleStackAnimation(owner, _stack),
  273. prevHex(prevHex),
  274. nextHex(nextHex)
  275. {
  276. }
  277. bool MovementAnimation::init()
  278. {
  279. assert(stack);
  280. assert(!myAnim->isDeadOrDying());
  281. assert(stackAnimation(stack)->framesInGroup(ECreatureAnimType::MOVING) > 0);
  282. if(stackAnimation(stack)->framesInGroup(ECreatureAnimType::MOVING) == 0)
  283. {
  284. //no movement, end immediately
  285. delete this;
  286. return false;
  287. }
  288. logAnim->debug("CMovementAnimation::init: stack %s moves %d -> %d", stack->getName(), prevHex, nextHex);
  289. //reverse unit if necessary
  290. if(owner.stacksController->shouldRotate(stack, prevHex, nextHex))
  291. {
  292. // it seems that H3 does NOT plays full rotation animation during movement
  293. // Logical since it takes quite a lot of time
  294. rotateStack(prevHex);
  295. }
  296. if(myAnim->getType() != ECreatureAnimType::MOVING)
  297. {
  298. myAnim->setType(ECreatureAnimType::MOVING);
  299. }
  300. if (moveSoundHandler == -1)
  301. {
  302. moveSoundHandler = CCS->soundh->playSound(stack->unitType()->sounds.move, -1);
  303. }
  304. Point begPosition = owner.stacksController->getStackPositionAtHex(prevHex, stack);
  305. Point endPosition = owner.stacksController->getStackPositionAtHex(nextHex, stack);
  306. progressPerSecond = AnimationControls::getMovementRange(stack->unitType());
  307. begX = begPosition.x;
  308. begY = begPosition.y;
  309. //progress = 0;
  310. distanceX = endPosition.x - begPosition.x;
  311. distanceY = endPosition.y - begPosition.y;
  312. if (stack->hasBonus(Selector::type()(BonusType::FLYING)))
  313. {
  314. float distance = static_cast<float>(sqrt(distanceX * distanceX + distanceY * distanceY));
  315. progressPerSecond = AnimationControls::getFlightDistance(stack->unitType()) / distance;
  316. }
  317. return true;
  318. }
  319. void MovementAnimation::tick(uint32_t msPassed)
  320. {
  321. progress += float(msPassed) / 1000 * progressPerSecond;
  322. //moving instructions
  323. myAnim->pos.x = begX + distanceX * progress;
  324. myAnim->pos.y = begY + distanceY * progress;
  325. BattleAnimation::tick(msPassed);
  326. if(progress >= 1.0)
  327. {
  328. progress -= 1.0;
  329. // Sets the position of the creature animation sprites
  330. Point coords = owner.stacksController->getStackPositionAtHex(nextHex, stack);
  331. myAnim->pos.moveTo(coords);
  332. // true if creature haven't reached the final destination hex
  333. if ((currentMoveIndex + 1) < destTiles.size())
  334. {
  335. // update the next hex field which has to be reached by the stack
  336. currentMoveIndex++;
  337. prevHex = nextHex;
  338. nextHex = destTiles[currentMoveIndex];
  339. // request re-initialization
  340. initialized = false;
  341. }
  342. else
  343. delete this;
  344. }
  345. }
  346. MovementAnimation::~MovementAnimation()
  347. {
  348. assert(stack);
  349. if(moveSoundHandler != -1)
  350. CCS->soundh->stopSound(moveSoundHandler);
  351. }
  352. MovementAnimation::MovementAnimation(BattleInterface & owner, const CStack *stack, const BattleHexArray & _destTiles, int _distance)
  353. : StackMoveAnimation(owner, stack, stack->getPosition(), _destTiles.front()),
  354. destTiles(_destTiles),
  355. currentMoveIndex(0),
  356. begX(0), begY(0),
  357. distanceX(0), distanceY(0),
  358. progressPerSecond(0.0),
  359. moveSoundHandler(-1),
  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(stack->unitType()->sounds.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(stack->unitType()->sounds.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::tick(uint32_t msPassed)
  480. {
  481. float elapsed = msPassed / 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(getCreature()->sounds.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 (absolute 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.upperRightMissileOffsetX ) * multiplier;
  554. shotOrigin.y += shooterInfo->animation.upperRightMissileOffsetY;
  555. }
  556. else if (getGroup() == getDownwardsGroup())
  557. {
  558. shotOrigin.x += ( -25 + shooterInfo->animation.lowerRightMissileOffsetX ) * multiplier;
  559. shotOrigin.y += shooterInfo->animation.lowerRightMissileOffsetY;
  560. }
  561. else if (getGroup() == getForwardGroup())
  562. {
  563. shotOrigin.x += ( -25 + shooterInfo->animation.rightMissileOffsetX ) * multiplier;
  564. shotOrigin.y += shooterInfo->animation.rightMissileOffsetY;
  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::tick(uint32_t msPassed)
  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. bool stackHasProjectile = owner.projectilesController->hasActiveProjectile(stack, true);
  587. if (!projectileEmitted || stackHasProjectile)
  588. stackAnimation(attackingStack)->playUntil(getAttackClimaxFrame());
  589. else
  590. stackAnimation(attackingStack)->playUntil(static_cast<size_t>(-1));
  591. AttackAnimation::tick(msPassed);
  592. if (!projectileEmitted)
  593. {
  594. // emit projectile once animation playback reached "climax" frame
  595. if ( stackAnimation(attackingStack)->getCurrentFrame() >= getAttackClimaxFrame() )
  596. {
  597. emitProjectile();
  598. return;
  599. }
  600. }
  601. }
  602. RangedAttackAnimation::~RangedAttackAnimation()
  603. {
  604. assert(!owner.projectilesController->hasActiveProjectile(attackingStack, false));
  605. assert(projectileEmitted);
  606. // FIXME: is this possible? Animation is over but we're yet to fire projectile?
  607. if (!projectileEmitted)
  608. {
  609. logAnim->warn("Shooting animation has finished but projectile was not emitted! Emitting it now...");
  610. emitProjectile();
  611. }
  612. }
  613. ShootingAnimation::ShootingAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
  614. : RangedAttackAnimation(owner, attacker, _dest, _attacked)
  615. {
  616. logAnim->debug("Created ShootingAnimation for %s", stack->getName());
  617. }
  618. void ShootingAnimation::createProjectile(const Point & from, const Point & dest) const
  619. {
  620. owner.projectilesController->createProjectile(attackingStack, from, dest);
  621. }
  622. uint32_t ShootingAnimation::getAttackClimaxFrame() const
  623. {
  624. const CCreature *shooterInfo = getCreature();
  625. uint32_t maxFrames = stackAnimation(attackingStack)->framesInGroup(getGroup());
  626. uint32_t climaxFrame = shooterInfo->animation.attackClimaxFrame;
  627. uint32_t selectedFrame = std::clamp<int>(shooterInfo->animation.attackClimaxFrame, 1, maxFrames);
  628. if (climaxFrame != selectedFrame)
  629. logGlobal->warn("Shooter %s has ranged attack climax frame set to %d, but only %d available!", shooterInfo->getNamePluralTranslated(), climaxFrame, maxFrames);
  630. return selectedFrame - 1; // H3 counts frames from 1
  631. }
  632. ECreatureAnimType ShootingAnimation::getUpwardsGroup() const
  633. {
  634. return ECreatureAnimType::SHOOT_UP;
  635. }
  636. ECreatureAnimType ShootingAnimation::getForwardGroup() const
  637. {
  638. return ECreatureAnimType::SHOOT_FRONT;
  639. }
  640. ECreatureAnimType ShootingAnimation::getDownwardsGroup() const
  641. {
  642. return ECreatureAnimType::SHOOT_DOWN;
  643. }
  644. CatapultAnimation::CatapultAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, int _catapultDmg)
  645. : ShootingAnimation(owner, attacker, _dest, _attacked),
  646. catapultDamage(_catapultDmg),
  647. explosionEmitted(false)
  648. {
  649. logAnim->debug("Created shooting anim for %s", stack->getName());
  650. }
  651. void CatapultAnimation::tick(uint32_t msPassed)
  652. {
  653. ShootingAnimation::tick(msPassed);
  654. if ( explosionEmitted)
  655. return;
  656. if ( !projectileEmitted)
  657. return;
  658. if (owner.projectilesController->hasActiveProjectile(attackingStack, false))
  659. return;
  660. explosionEmitted = true;
  661. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, defendingStack) + Point(225, 225) - Point(126, 105);
  662. auto soundFilename = AudioPath::builtin((catapultDamage > 0) ? "WALLHIT" : "WALLMISS");
  663. AnimationPath effectFilename = AnimationPath::builtin((catapultDamage > 0) ? "SGEXPL" : "CSGRCK");
  664. CCS->soundh->playSound( soundFilename );
  665. owner.stacksController->addNewAnim( new EffectAnimation(owner, effectFilename, shotTarget));
  666. }
  667. void CatapultAnimation::createProjectile(const Point & from, const Point & dest) const
  668. {
  669. owner.projectilesController->createCatapultProjectile(attackingStack, from, dest);
  670. }
  671. CastAnimation::CastAnimation(BattleInterface & owner_, const CStack * attacker, BattleHex dest, const CStack * defender, const CSpell * spell)
  672. : RangedAttackAnimation(owner_, attacker, dest, defender),
  673. spell(spell)
  674. {
  675. if(!dest.isValid())
  676. {
  677. assert(spell->animationInfo.projectile.empty());
  678. if (defender)
  679. dest = defender->getPosition();
  680. else
  681. dest = attacker->getPosition();
  682. }
  683. }
  684. ECreatureAnimType CastAnimation::getUpwardsGroup() const
  685. {
  686. return findValidGroup({
  687. ECreatureAnimType::CAST_UP,
  688. ECreatureAnimType::SPECIAL_UP,
  689. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  690. ECreatureAnimType::SHOOT_UP,
  691. ECreatureAnimType::ATTACK_UP
  692. });
  693. }
  694. ECreatureAnimType CastAnimation::getForwardGroup() const
  695. {
  696. return findValidGroup({
  697. ECreatureAnimType::CAST_FRONT,
  698. ECreatureAnimType::SPECIAL_FRONT,
  699. ECreatureAnimType::SHOOT_FRONT,
  700. ECreatureAnimType::ATTACK_FRONT
  701. });
  702. }
  703. ECreatureAnimType CastAnimation::getDownwardsGroup() const
  704. {
  705. return findValidGroup({
  706. ECreatureAnimType::CAST_DOWN,
  707. ECreatureAnimType::SPECIAL_DOWN,
  708. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  709. ECreatureAnimType::SHOOT_DOWN,
  710. ECreatureAnimType::ATTACK_DOWN
  711. });
  712. }
  713. void CastAnimation::createProjectile(const Point & from, const Point & dest) const
  714. {
  715. if (!spell->animationInfo.projectile.empty())
  716. owner.projectilesController->createSpellProjectile(attackingStack, from, dest, spell);
  717. }
  718. uint32_t CastAnimation::getAttackClimaxFrame() const
  719. {
  720. //TODO: allow defining this parameter in config file, separately from attackClimaxFrame of missile attacks
  721. uint32_t maxFrames = stackAnimation(attackingStack)->framesInGroup(getGroup());
  722. return maxFrames / 2;
  723. }
  724. EffectAnimation::EffectAnimation(BattleInterface & owner, const AnimationPath & animationName, int effects, float transparencyFactor, bool reversed):
  725. BattleAnimation(owner),
  726. animation(GH.renderHandler().loadAnimation(animationName, EImageBlitMode::SIMPLE)),
  727. transparencyFactor(transparencyFactor),
  728. effectFlags(effects),
  729. effectFinished(false),
  730. reversed(reversed)
  731. {
  732. logAnim->debug("CPointEffectAnimation::init: effect %s", animationName.getName());
  733. }
  734. EffectAnimation::EffectAnimation(BattleInterface & owner, const AnimationPath & animationName, const BattleHexArray & hexes, int effects, bool reversed):
  735. EffectAnimation(owner, animationName, effects, 1.0f, reversed)
  736. {
  737. battlehexes = hexes;
  738. }
  739. EffectAnimation::EffectAnimation(BattleInterface & owner, const AnimationPath & animationName, BattleHex hex, int effects, float transparencyFactor, bool reversed):
  740. EffectAnimation(owner, animationName, effects, transparencyFactor, reversed)
  741. {
  742. assert(hex.isValid());
  743. battlehexes.insert(hex);
  744. }
  745. EffectAnimation::EffectAnimation(BattleInterface & owner, const AnimationPath & animationName, std::vector<Point> pos, int effects, bool reversed):
  746. EffectAnimation(owner, animationName, effects, 1.0f, reversed)
  747. {
  748. positions = pos;
  749. }
  750. EffectAnimation::EffectAnimation(BattleInterface & owner, const AnimationPath & animationName, Point pos, int effects, bool reversed):
  751. EffectAnimation(owner, animationName, effects, 1.0f, reversed)
  752. {
  753. positions.push_back(pos);
  754. }
  755. EffectAnimation::EffectAnimation(BattleInterface & owner, const AnimationPath & animationName, Point pos, BattleHex hex, int effects, bool reversed):
  756. EffectAnimation(owner, animationName, effects, 1.0f, reversed)
  757. {
  758. assert(hex.isValid());
  759. battlehexes.insert(hex);
  760. positions.push_back(pos);
  761. }
  762. bool EffectAnimation::init()
  763. {
  764. auto first = animation->getImage(0, 0, true);
  765. if(!first)
  766. {
  767. delete this;
  768. return false;
  769. }
  770. for (size_t i = 0; i < animation->size(size_t(BattleEffect::AnimType::DEFAULT)); ++i)
  771. {
  772. size_t current = animation->size(size_t(BattleEffect::AnimType::DEFAULT)) - 1 - i;
  773. animation->duplicateImage(size_t(BattleEffect::AnimType::DEFAULT), current, size_t(BattleEffect::AnimType::REVERSE));
  774. }
  775. if (screenFill())
  776. {
  777. for(int i=0; i * first->width() < owner.fieldController->pos.w ; ++i)
  778. for(int j=0; j * first->height() < owner.fieldController->pos.h ; ++j)
  779. positions.push_back(Point( i * first->width(), j * first->height()));
  780. }
  781. BattleEffect be;
  782. be.effectID = ID;
  783. be.animation = animation;
  784. be.currentFrame = 0;
  785. be.transparencyFactor = transparencyFactor;
  786. be.type = reversed ? BattleEffect::AnimType::REVERSE : BattleEffect::AnimType::DEFAULT;
  787. for (size_t i = 0; i < std::max(battlehexes.size(), positions.size()); ++i)
  788. {
  789. bool hasTile = i < battlehexes.size();
  790. bool hasPosition = i < positions.size();
  791. if (hasTile && !forceOnTop())
  792. be.tile = battlehexes[i];
  793. else
  794. be.tile = BattleHex::INVALID;
  795. if (hasPosition)
  796. {
  797. be.pos.x = positions[i].x;
  798. be.pos.y = positions[i].y;
  799. }
  800. else
  801. {
  802. const auto * destStack = owner.getBattle()->battleGetUnitByPos(battlehexes[i], false);
  803. Rect tilePos = owner.fieldController->hexPositionLocal(battlehexes[i]);
  804. be.pos.x = tilePos.x + tilePos.w/2 - first->width()/2;
  805. if(destStack && destStack->doubleWide()) // Correction for 2-hex creatures.
  806. be.pos.x += (destStack->unitSide() == BattleSide::ATTACKER ? -1 : 1)*tilePos.w/2;
  807. if (alignToBottom())
  808. be.pos.y = tilePos.y + tilePos.h - first->height();
  809. else
  810. be.pos.y = tilePos.y - first->height()/2;
  811. }
  812. owner.effectsController->battleEffects.push_back(be);
  813. }
  814. return true;
  815. }
  816. void EffectAnimation::tick(uint32_t msPassed)
  817. {
  818. playEffect(msPassed);
  819. if (effectFinished)
  820. {
  821. //remove visual effect itself only if sound has finished as well - necessary for obstacles like force field
  822. clearEffect();
  823. delete this;
  824. }
  825. }
  826. bool EffectAnimation::alignToBottom() const
  827. {
  828. return effectFlags & ALIGN_TO_BOTTOM;
  829. }
  830. bool EffectAnimation::forceOnTop() const
  831. {
  832. return effectFlags & FORCE_ON_TOP;
  833. }
  834. bool EffectAnimation::screenFill() const
  835. {
  836. return effectFlags & SCREEN_FILL;
  837. }
  838. void EffectAnimation::onEffectFinished()
  839. {
  840. effectFinished = true;
  841. }
  842. void EffectAnimation::playEffect(uint32_t msPassed)
  843. {
  844. if ( effectFinished )
  845. return;
  846. for(auto & elem : owner.effectsController->battleEffects)
  847. {
  848. if(elem.effectID == ID)
  849. {
  850. elem.currentFrame += AnimationControls::getSpellEffectSpeed() * msPassed / 1000;
  851. if(elem.currentFrame >= elem.animation->size())
  852. {
  853. elem.currentFrame = elem.animation->size() - 1;
  854. onEffectFinished();
  855. break;
  856. }
  857. }
  858. }
  859. }
  860. void EffectAnimation::clearEffect()
  861. {
  862. auto & effects = owner.effectsController->battleEffects;
  863. vstd::erase_if(effects, [&](const BattleEffect & effect){
  864. return effect.effectID == ID;
  865. });
  866. }
  867. EffectAnimation::~EffectAnimation()
  868. {
  869. assert(effectFinished);
  870. }
  871. HeroCastAnimation::HeroCastAnimation(BattleInterface & owner, std::shared_ptr<BattleHero> hero, BattleHex dest, const CStack * defender, const CSpell * spell):
  872. BattleAnimation(owner),
  873. projectileEmitted(false),
  874. hero(hero),
  875. target(defender),
  876. tile(dest),
  877. spell(spell)
  878. {
  879. }
  880. bool HeroCastAnimation::init()
  881. {
  882. hero->setPhase(EHeroAnimType::CAST_SPELL);
  883. hero->onPhaseFinished([&](){
  884. delete this;
  885. });
  886. initializeProjectile();
  887. return true;
  888. }
  889. void HeroCastAnimation::initializeProjectile()
  890. {
  891. // spell has no projectile to play, ignore this step
  892. if (spell->animationInfo.projectile.empty())
  893. return;
  894. // targeted spells should have well, target
  895. assert(tile.isValid());
  896. Point srccoord = hero->pos.center() - hero->parent->pos.topLeft();
  897. Point destcoord = owner.stacksController->getStackPositionAtHex(tile, target); //position attacked by projectile
  898. destcoord += Point(222, 265); // FIXME: what are these constants?
  899. owner.projectilesController->createSpellProjectile( nullptr, srccoord, destcoord, spell);
  900. }
  901. void HeroCastAnimation::emitProjectile()
  902. {
  903. if (projectileEmitted)
  904. return;
  905. //spell has no projectile to play, skip this step and immediately play hit animations
  906. if (spell->animationInfo.projectile.empty())
  907. emitAnimationEvent();
  908. else
  909. owner.projectilesController->emitStackProjectile( nullptr );
  910. projectileEmitted = true;
  911. }
  912. void HeroCastAnimation::emitAnimationEvent()
  913. {
  914. owner.executeAnimationStage(EAnimationEvents::HIT);
  915. }
  916. void HeroCastAnimation::tick(uint32_t msPassed)
  917. {
  918. float frame = hero->getFrame();
  919. if (frame < 4.0f) // middle point of animation //TODO: un-hardcode
  920. return;
  921. if (!projectileEmitted)
  922. {
  923. emitProjectile();
  924. hero->pause();
  925. return;
  926. }
  927. if (!owner.projectilesController->hasActiveProjectile(nullptr, false))
  928. {
  929. emitAnimationEvent();
  930. //TODO: check H3 - it is possible that hero animation should be paused until hit effect is over, not just projectile
  931. hero->play();
  932. }
  933. }