BattleAnimationClasses.cpp 30 KB

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