BattleAnimationClasses.cpp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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() && currGroup != ECreatureAnimType::DEATH && currGroup != ECreatureAnimType::DEATH_RANGED)
  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->unitType()->getId() == CreatureID::ARROW_TOWERS)
  136. return owner.siegeController->getTurretCreature();
  137. else
  138. return attackingStack->unitType();
  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->unitType(), 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->unitType(), 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->unitType(), 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 (moveSoundHander == -1)
  299. {
  300. moveSoundHander = CCS->soundh->playSound(battle_sound(stack->unitType(), move), -1);
  301. }
  302. Point begPosition = owner.stacksController->getStackPositionAtHex(prevHex, stack);
  303. Point endPosition = owner.stacksController->getStackPositionAtHex(nextHex, stack);
  304. progressPerSecond = AnimationControls::getMovementDistance(stack->unitType());
  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->unitType()) / 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(moveSoundHander != -1)
  348. CCS->soundh->stopSound(moveSoundHander);
  349. }
  350. MovementAnimation::MovementAnimation(BattleInterface & owner, const CStack *stack, std::vector<BattleHex> _destTiles, int _distance)
  351. : StackMoveAnimation(owner, stack, stack->getPosition(), _destTiles.front()),
  352. destTiles(_destTiles),
  353. curentMoveIndex(0),
  354. begX(0), begY(0),
  355. distanceX(0), distanceY(0),
  356. progressPerSecond(0.0),
  357. moveSoundHander(-1),
  358. progress(0.0)
  359. {
  360. logAnim->debug("Created MovementAnimation for %s", stack->getName());
  361. }
  362. MovementEndAnimation::MovementEndAnimation(BattleInterface & owner, const CStack * _stack, BattleHex destTile)
  363. : StackMoveAnimation(owner, _stack, destTile, destTile)
  364. {
  365. logAnim->debug("Created MovementEndAnimation for %s", stack->getName());
  366. }
  367. bool MovementEndAnimation::init()
  368. {
  369. assert(stack);
  370. assert(!myAnim->isDeadOrDying());
  371. if(!stack || myAnim->isDeadOrDying())
  372. {
  373. delete this;
  374. return false;
  375. }
  376. logAnim->debug("CMovementEndAnimation::init: stack %s", stack->getName());
  377. myAnim->pos.moveTo(owner.stacksController->getStackPositionAtHex(nextHex, stack));
  378. CCS->soundh->playSound(battle_sound(stack->unitType(), endMoving));
  379. if(!myAnim->framesInGroup(ECreatureAnimType::MOVE_END))
  380. {
  381. delete this;
  382. return false;
  383. }
  384. myAnim->setType(ECreatureAnimType::MOVE_END);
  385. myAnim->onAnimationReset += [&](){ delete this; };
  386. return true;
  387. }
  388. MovementEndAnimation::~MovementEndAnimation()
  389. {
  390. if(myAnim->getType() != ECreatureAnimType::DEAD)
  391. myAnim->setType(ECreatureAnimType::HOLDING); //resetting to default
  392. CCS->curh->show();
  393. }
  394. MovementStartAnimation::MovementStartAnimation(BattleInterface & owner, const CStack * _stack)
  395. : StackMoveAnimation(owner, _stack, _stack->getPosition(), _stack->getPosition())
  396. {
  397. logAnim->debug("Created MovementStartAnimation for %s", stack->getName());
  398. }
  399. bool MovementStartAnimation::init()
  400. {
  401. assert(stack);
  402. assert(!myAnim->isDeadOrDying());
  403. if(!stack || myAnim->isDeadOrDying())
  404. {
  405. delete this;
  406. return false;
  407. }
  408. logAnim->debug("CMovementStartAnimation::init: stack %s", stack->getName());
  409. CCS->soundh->playSound(battle_sound(stack->unitType(), startMoving));
  410. if(!myAnim->framesInGroup(ECreatureAnimType::MOVE_START))
  411. {
  412. delete this;
  413. return false;
  414. }
  415. myAnim->setType(ECreatureAnimType::MOVE_START);
  416. myAnim->onAnimationReset += [&](){ delete this; };
  417. return true;
  418. }
  419. ReverseAnimation::ReverseAnimation(BattleInterface & owner, const CStack * stack, BattleHex dest)
  420. : StackMoveAnimation(owner, stack, dest, dest)
  421. {
  422. logAnim->debug("Created ReverseAnimation for %s", stack->getName());
  423. }
  424. bool ReverseAnimation::init()
  425. {
  426. assert(myAnim);
  427. assert(!myAnim->isDeadOrDying());
  428. if(myAnim == nullptr || myAnim->isDeadOrDying())
  429. {
  430. delete this;
  431. return false; //there is no such creature
  432. }
  433. logAnim->debug("CReverseAnimation::init: stack %s", stack->getName());
  434. if(myAnim->framesInGroup(ECreatureAnimType::TURN_L))
  435. {
  436. myAnim->playOnce(ECreatureAnimType::TURN_L);
  437. myAnim->onAnimationReset += std::bind(&ReverseAnimation::setupSecondPart, this);
  438. }
  439. else
  440. {
  441. setupSecondPart();
  442. }
  443. return true;
  444. }
  445. void BattleStackAnimation::rotateStack(BattleHex hex)
  446. {
  447. setStackFacingRight(stack, !stackFacingRight(stack));
  448. stackAnimation(stack)->pos.moveTo(owner.stacksController->getStackPositionAtHex(hex, stack));
  449. }
  450. void ReverseAnimation::setupSecondPart()
  451. {
  452. assert(stack);
  453. if(!stack)
  454. {
  455. delete this;
  456. return;
  457. }
  458. rotateStack(nextHex);
  459. if(myAnim->framesInGroup(ECreatureAnimType::TURN_R))
  460. {
  461. myAnim->playOnce(ECreatureAnimType::TURN_R);
  462. myAnim->onAnimationReset += [&](){ delete this; };
  463. }
  464. else
  465. delete this;
  466. }
  467. ResurrectionAnimation::ResurrectionAnimation(BattleInterface & owner, const CStack * _stack):
  468. StackActionAnimation(owner, _stack)
  469. {
  470. setGroup(ECreatureAnimType::RESURRECTION);
  471. logAnim->debug("Created ResurrectionAnimation for %s", stack->getName());
  472. }
  473. bool ColorTransformAnimation::init()
  474. {
  475. return true;
  476. }
  477. void ColorTransformAnimation::nextFrame()
  478. {
  479. float elapsed = GH.mainFPSmng->getElapsedMilliseconds() / 1000.f;
  480. float fullTime = AnimationControls::getFadeInDuration();
  481. float delta = elapsed / fullTime;
  482. totalProgress += delta;
  483. size_t index = 0;
  484. while (index < timePoints.size() && timePoints[index] < totalProgress )
  485. ++index;
  486. if (index == timePoints.size())
  487. {
  488. //end of animation. Apply ColorShifter using final values and die
  489. const auto & shifter = steps[index - 1];
  490. owner.stacksController->setStackColorFilter(shifter, stack, spell, false);
  491. delete this;
  492. return;
  493. }
  494. assert(index != 0);
  495. const auto & prevShifter = steps[index - 1];
  496. const auto & nextShifter = steps[index];
  497. float prevPoint = timePoints[index-1];
  498. float nextPoint = timePoints[index];
  499. float localProgress = totalProgress - prevPoint;
  500. float stepDuration = (nextPoint - prevPoint);
  501. float factor = localProgress / stepDuration;
  502. auto shifter = ColorFilter::genInterpolated(prevShifter, nextShifter, factor);
  503. owner.stacksController->setStackColorFilter(shifter, stack, spell, true);
  504. }
  505. ColorTransformAnimation::ColorTransformAnimation(BattleInterface & owner, const CStack * _stack, const std::string & colorFilterName, const CSpell * spell):
  506. BattleStackAnimation(owner, _stack),
  507. spell(spell),
  508. totalProgress(0.f)
  509. {
  510. auto effect = owner.effectsController->getMuxerEffect(colorFilterName);
  511. steps = effect.filters;
  512. timePoints = effect.timePoints;
  513. assert(!steps.empty() && steps.size() == timePoints.size());
  514. logAnim->debug("Created ColorTransformAnimation for %s", stack->getName());
  515. }
  516. RangedAttackAnimation::RangedAttackAnimation(BattleInterface & owner_, const CStack * attacker, BattleHex dest_, const CStack * defender)
  517. : AttackAnimation(owner_, attacker, dest_, defender),
  518. projectileEmitted(false)
  519. {
  520. setSound(battle_sound(getCreature(), shoot));
  521. }
  522. bool RangedAttackAnimation::init()
  523. {
  524. setAnimationGroup();
  525. initializeProjectile();
  526. return AttackAnimation::init();
  527. }
  528. void RangedAttackAnimation::setAnimationGroup()
  529. {
  530. Point shooterPos = stackAnimation(attackingStack)->pos.topLeft();
  531. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, defendingStack);
  532. //maximal angle in radians between straight horizontal line and shooting line for which shot is considered to be straight (absoulte value)
  533. static const double straightAngle = 0.2;
  534. double projectileAngle = -atan2(shotTarget.y - shooterPos.y, std::abs(shotTarget.x - shooterPos.x));
  535. // Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
  536. if (projectileAngle > straightAngle)
  537. setGroup(getUpwardsGroup());
  538. else if (projectileAngle < -straightAngle)
  539. setGroup(getDownwardsGroup());
  540. else
  541. setGroup(getForwardGroup());
  542. }
  543. void RangedAttackAnimation::initializeProjectile()
  544. {
  545. const CCreature *shooterInfo = getCreature();
  546. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, defendingStack) + Point(225, 225);
  547. Point shotOrigin = stackAnimation(attackingStack)->pos.topLeft() + Point(222, 265);
  548. int multiplier = stackFacingRight(attackingStack) ? 1 : -1;
  549. if (getGroup() == getUpwardsGroup())
  550. {
  551. shotOrigin.x += ( -25 + shooterInfo->animation.upperRightMissleOffsetX ) * multiplier;
  552. shotOrigin.y += shooterInfo->animation.upperRightMissleOffsetY;
  553. }
  554. else if (getGroup() == getDownwardsGroup())
  555. {
  556. shotOrigin.x += ( -25 + shooterInfo->animation.lowerRightMissleOffsetX ) * multiplier;
  557. shotOrigin.y += shooterInfo->animation.lowerRightMissleOffsetY;
  558. }
  559. else if (getGroup() == getForwardGroup())
  560. {
  561. shotOrigin.x += ( -25 + shooterInfo->animation.rightMissleOffsetX ) * multiplier;
  562. shotOrigin.y += shooterInfo->animation.rightMissleOffsetY;
  563. }
  564. else
  565. {
  566. assert(0);
  567. }
  568. createProjectile(shotOrigin, shotTarget);
  569. }
  570. void RangedAttackAnimation::emitProjectile()
  571. {
  572. logAnim->debug("Ranged attack projectile emitted");
  573. owner.projectilesController->emitStackProjectile(attackingStack);
  574. projectileEmitted = true;
  575. }
  576. void RangedAttackAnimation::nextFrame()
  577. {
  578. // animation should be paused if there is an active projectile
  579. if (projectileEmitted)
  580. {
  581. if (!owner.projectilesController->hasActiveProjectile(attackingStack, false))
  582. owner.executeAnimationStage(EAnimationEvents::HIT);
  583. }
  584. bool stackHasProjectile = owner.projectilesController->hasActiveProjectile(stack, true);
  585. if (!projectileEmitted || stackHasProjectile)
  586. stackAnimation(attackingStack)->playUntil(getAttackClimaxFrame());
  587. else
  588. stackAnimation(attackingStack)->playUntil(static_cast<size_t>(-1));
  589. AttackAnimation::nextFrame();
  590. if (!projectileEmitted)
  591. {
  592. // emit projectile once animation playback reached "climax" frame
  593. if ( stackAnimation(attackingStack)->getCurrentFrame() >= getAttackClimaxFrame() )
  594. {
  595. emitProjectile();
  596. return;
  597. }
  598. }
  599. }
  600. RangedAttackAnimation::~RangedAttackAnimation()
  601. {
  602. assert(!owner.projectilesController->hasActiveProjectile(attackingStack, false));
  603. assert(projectileEmitted);
  604. // FIXME: is this possible? Animation is over but we're yet to fire projectile?
  605. if (!projectileEmitted)
  606. {
  607. logAnim->warn("Shooting animation has finished but projectile was not emitted! Emitting it now...");
  608. emitProjectile();
  609. }
  610. }
  611. ShootingAnimation::ShootingAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
  612. : RangedAttackAnimation(owner, attacker, _dest, _attacked)
  613. {
  614. logAnim->debug("Created ShootingAnimation for %s", stack->getName());
  615. }
  616. void ShootingAnimation::createProjectile(const Point & from, const Point & dest) const
  617. {
  618. owner.projectilesController->createProjectile(attackingStack, from, dest);
  619. }
  620. uint32_t ShootingAnimation::getAttackClimaxFrame() const
  621. {
  622. const CCreature *shooterInfo = getCreature();
  623. uint32_t maxFrames = stackAnimation(attackingStack)->framesInGroup(getGroup());
  624. uint32_t climaxFrame = shooterInfo->animation.attackClimaxFrame;
  625. uint32_t selectedFrame = std::clamp<int>(shooterInfo->animation.attackClimaxFrame, 1, maxFrames);
  626. if (climaxFrame != selectedFrame)
  627. logGlobal->warn("Shooter %s has ranged attack climax frame set to %d, but only %d available!", shooterInfo->getNamePluralTranslated(), climaxFrame, maxFrames);
  628. return selectedFrame - 1; // H3 counts frames from 1
  629. }
  630. ECreatureAnimType ShootingAnimation::getUpwardsGroup() const
  631. {
  632. return ECreatureAnimType::SHOOT_UP;
  633. }
  634. ECreatureAnimType ShootingAnimation::getForwardGroup() const
  635. {
  636. return ECreatureAnimType::SHOOT_FRONT;
  637. }
  638. ECreatureAnimType ShootingAnimation::getDownwardsGroup() const
  639. {
  640. return ECreatureAnimType::SHOOT_DOWN;
  641. }
  642. CatapultAnimation::CatapultAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, int _catapultDmg)
  643. : ShootingAnimation(owner, attacker, _dest, _attacked),
  644. catapultDamage(_catapultDmg),
  645. explosionEmitted(false)
  646. {
  647. logAnim->debug("Created shooting anim for %s", stack->getName());
  648. }
  649. void CatapultAnimation::nextFrame()
  650. {
  651. ShootingAnimation::nextFrame();
  652. if ( explosionEmitted)
  653. return;
  654. if ( !projectileEmitted)
  655. return;
  656. if (owner.projectilesController->hasActiveProjectile(attackingStack, false))
  657. return;
  658. explosionEmitted = true;
  659. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, defendingStack) + Point(225, 225) - Point(126, 105);
  660. std::string soundFilename = (catapultDamage > 0) ? "WALLHIT" : "WALLMISS";
  661. std::string effectFilename = (catapultDamage > 0) ? "SGEXPL" : "CSGRCK";
  662. CCS->soundh->playSound( soundFilename );
  663. owner.stacksController->addNewAnim( new EffectAnimation(owner, effectFilename, shotTarget));
  664. }
  665. void CatapultAnimation::createProjectile(const Point & from, const Point & dest) const
  666. {
  667. owner.projectilesController->createCatapultProjectile(attackingStack, from, dest);
  668. }
  669. CastAnimation::CastAnimation(BattleInterface & owner_, const CStack * attacker, BattleHex dest, const CStack * defender, const CSpell * spell)
  670. : RangedAttackAnimation(owner_, attacker, dest, defender),
  671. spell(spell)
  672. {
  673. if(!dest.isValid())
  674. {
  675. assert(spell->animationInfo.projectile.empty());
  676. if (defender)
  677. dest = defender->getPosition();
  678. else
  679. dest = attacker->getPosition();
  680. }
  681. }
  682. ECreatureAnimType CastAnimation::getUpwardsGroup() const
  683. {
  684. return findValidGroup({
  685. ECreatureAnimType::CAST_UP,
  686. ECreatureAnimType::SPECIAL_UP,
  687. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  688. ECreatureAnimType::SHOOT_UP,
  689. ECreatureAnimType::ATTACK_UP
  690. });
  691. }
  692. ECreatureAnimType CastAnimation::getForwardGroup() const
  693. {
  694. return findValidGroup({
  695. ECreatureAnimType::CAST_FRONT,
  696. ECreatureAnimType::SPECIAL_FRONT,
  697. ECreatureAnimType::SHOOT_FRONT,
  698. ECreatureAnimType::ATTACK_FRONT
  699. });
  700. }
  701. ECreatureAnimType CastAnimation::getDownwardsGroup() const
  702. {
  703. return findValidGroup({
  704. ECreatureAnimType::CAST_DOWN,
  705. ECreatureAnimType::SPECIAL_DOWN,
  706. ECreatureAnimType::SPECIAL_FRONT, // weird, but required for H3
  707. ECreatureAnimType::SHOOT_DOWN,
  708. ECreatureAnimType::ATTACK_DOWN
  709. });
  710. }
  711. void CastAnimation::createProjectile(const Point & from, const Point & dest) const
  712. {
  713. if (!spell->animationInfo.projectile.empty())
  714. owner.projectilesController->createSpellProjectile(attackingStack, from, dest, spell);
  715. }
  716. uint32_t CastAnimation::getAttackClimaxFrame() const
  717. {
  718. //TODO: allow defining this parameter in config file, separately from attackClimaxFrame of missile attacks
  719. uint32_t maxFrames = stackAnimation(attackingStack)->framesInGroup(getGroup());
  720. return maxFrames / 2;
  721. }
  722. EffectAnimation::EffectAnimation(BattleInterface & owner, std::string animationName, int effects, bool reversed):
  723. BattleAnimation(owner),
  724. animation(std::make_shared<CAnimation>(animationName)),
  725. effectFlags(effects),
  726. effectFinished(false),
  727. reversed(reversed)
  728. {
  729. logAnim->debug("CPointEffectAnimation::init: effect %s", animationName);
  730. }
  731. EffectAnimation::EffectAnimation(BattleInterface & owner, std::string animationName, std::vector<BattleHex> hex, int effects, bool reversed):
  732. EffectAnimation(owner, animationName, effects, reversed)
  733. {
  734. battlehexes = hex;
  735. }
  736. EffectAnimation::EffectAnimation(BattleInterface & owner, std::string animationName, BattleHex hex, int effects, bool reversed):
  737. EffectAnimation(owner, animationName, effects, reversed)
  738. {
  739. assert(hex.isValid());
  740. battlehexes.push_back(hex);
  741. }
  742. EffectAnimation::EffectAnimation(BattleInterface & owner, std::string animationName, std::vector<Point> pos, int effects, bool reversed):
  743. EffectAnimation(owner, animationName, effects, reversed)
  744. {
  745. positions = pos;
  746. }
  747. EffectAnimation::EffectAnimation(BattleInterface & owner, std::string animationName, Point pos, int effects, bool reversed):
  748. EffectAnimation(owner, animationName, effects, reversed)
  749. {
  750. positions.push_back(pos);
  751. }
  752. EffectAnimation::EffectAnimation(BattleInterface & owner, std::string animationName, Point pos, BattleHex hex, int effects, bool reversed):
  753. EffectAnimation(owner, animationName, effects, reversed)
  754. {
  755. assert(hex.isValid());
  756. battlehexes.push_back(hex);
  757. positions.push_back(pos);
  758. }
  759. bool EffectAnimation::init()
  760. {
  761. animation->preload();
  762. auto first = animation->getImage(0, 0, true);
  763. if(!first)
  764. {
  765. delete this;
  766. return false;
  767. }
  768. for (size_t i = 0; i < animation->size(size_t(BattleEffect::AnimType::DEFAULT)); ++i)
  769. {
  770. size_t current = animation->size(size_t(BattleEffect::AnimType::DEFAULT)) - 1 - i;
  771. animation->duplicateImage(size_t(BattleEffect::AnimType::DEFAULT), current, size_t(BattleEffect::AnimType::REVERSE));
  772. }
  773. if (screenFill())
  774. {
  775. for(int i=0; i * first->width() < owner.fieldController->pos.w ; ++i)
  776. for(int j=0; j * first->height() < owner.fieldController->pos.h ; ++j)
  777. positions.push_back(Point( i * first->width(), j * first->height()));
  778. }
  779. BattleEffect be;
  780. be.effectID = ID;
  781. be.animation = animation;
  782. be.currentFrame = 0;
  783. be.type = reversed ? BattleEffect::AnimType::REVERSE : BattleEffect::AnimType::DEFAULT;
  784. for (size_t i = 0; i < std::max(battlehexes.size(), positions.size()); ++i)
  785. {
  786. bool hasTile = i < battlehexes.size();
  787. bool hasPosition = i < positions.size();
  788. if (hasTile && !forceOnTop())
  789. be.tile = battlehexes[i];
  790. else
  791. be.tile = BattleHex::INVALID;
  792. if (hasPosition)
  793. {
  794. be.pos.x = positions[i].x;
  795. be.pos.y = positions[i].y;
  796. }
  797. else
  798. {
  799. const auto * destStack = owner.getCurrentPlayerInterface()->cb->battleGetUnitByPos(battlehexes[i], false);
  800. Rect tilePos = owner.fieldController->hexPositionLocal(battlehexes[i]);
  801. be.pos.x = tilePos.x + tilePos.w/2 - first->width()/2;
  802. if(destStack && destStack->doubleWide()) // Correction for 2-hex creatures.
  803. be.pos.x += (destStack->unitSide() == BattleSide::ATTACKER ? -1 : 1)*tilePos.w/2;
  804. if (alignToBottom())
  805. be.pos.y = tilePos.y + tilePos.h - first->height();
  806. else
  807. be.pos.y = tilePos.y - first->height()/2;
  808. }
  809. owner.effectsController->battleEffects.push_back(be);
  810. }
  811. return true;
  812. }
  813. void EffectAnimation::nextFrame()
  814. {
  815. playEffect();
  816. if (effectFinished)
  817. {
  818. //remove visual effect itself only if sound has finished as well - necessary for obstacles like force field
  819. clearEffect();
  820. delete this;
  821. }
  822. }
  823. bool EffectAnimation::alignToBottom() const
  824. {
  825. return effectFlags & ALIGN_TO_BOTTOM;
  826. }
  827. bool EffectAnimation::forceOnTop() const
  828. {
  829. return effectFlags & FORCE_ON_TOP;
  830. }
  831. bool EffectAnimation::screenFill() const
  832. {
  833. return effectFlags & SCREEN_FILL;
  834. }
  835. void EffectAnimation::onEffectFinished()
  836. {
  837. effectFinished = true;
  838. }
  839. void EffectAnimation::playEffect()
  840. {
  841. if ( effectFinished )
  842. return;
  843. for(auto & elem : owner.effectsController->battleEffects)
  844. {
  845. if(elem.effectID == ID)
  846. {
  847. elem.currentFrame += AnimationControls::getSpellEffectSpeed() * GH.mainFPSmng->getElapsedMilliseconds() / 1000;
  848. if(elem.currentFrame >= elem.animation->size())
  849. {
  850. elem.currentFrame = elem.animation->size() - 1;
  851. onEffectFinished();
  852. break;
  853. }
  854. }
  855. }
  856. }
  857. void EffectAnimation::clearEffect()
  858. {
  859. auto & effects = owner.effectsController->battleEffects;
  860. vstd::erase_if(effects, [&](const BattleEffect & effect){
  861. return effect.effectID == ID;
  862. });
  863. }
  864. EffectAnimation::~EffectAnimation()
  865. {
  866. assert(effectFinished);
  867. }
  868. HeroCastAnimation::HeroCastAnimation(BattleInterface & owner, std::shared_ptr<BattleHero> hero, BattleHex dest, const CStack * defender, const CSpell * spell):
  869. BattleAnimation(owner),
  870. projectileEmitted(false),
  871. hero(hero),
  872. target(defender),
  873. tile(dest),
  874. spell(spell)
  875. {
  876. }
  877. bool HeroCastAnimation::init()
  878. {
  879. hero->setPhase(EHeroAnimType::CAST_SPELL);
  880. hero->onPhaseFinished([&](){
  881. delete this;
  882. });
  883. initializeProjectile();
  884. return true;
  885. }
  886. void HeroCastAnimation::initializeProjectile()
  887. {
  888. // spell has no projectile to play, ignore this step
  889. if (spell->animationInfo.projectile.empty())
  890. return;
  891. // targeted spells should have well, target
  892. assert(tile.isValid());
  893. Point srccoord = hero->pos.center() - hero->parent->pos.topLeft();
  894. Point destcoord = owner.stacksController->getStackPositionAtHex(tile, target); //position attacked by projectile
  895. destcoord += Point(222, 265); // FIXME: what are these constants?
  896. owner.projectilesController->createSpellProjectile( nullptr, srccoord, destcoord, spell);
  897. }
  898. void HeroCastAnimation::emitProjectile()
  899. {
  900. if (projectileEmitted)
  901. return;
  902. //spell has no projectile to play, skip this step and immediately play hit animations
  903. if (spell->animationInfo.projectile.empty())
  904. emitAnimationEvent();
  905. else
  906. owner.projectilesController->emitStackProjectile( nullptr );
  907. projectileEmitted = true;
  908. }
  909. void HeroCastAnimation::emitAnimationEvent()
  910. {
  911. owner.executeAnimationStage(EAnimationEvents::HIT);
  912. }
  913. void HeroCastAnimation::nextFrame()
  914. {
  915. float frame = hero->getFrame();
  916. if (frame < 4.0f) // middle point of animation //TODO: un-hardcode
  917. return;
  918. if (!projectileEmitted)
  919. {
  920. emitProjectile();
  921. hero->pause();
  922. return;
  923. }
  924. if (!owner.projectilesController->hasActiveProjectile(nullptr, false))
  925. {
  926. emitAnimationEvent();
  927. //TODO: check H3 - it is possible that hero animation should be paused until hit effect is over, not just projectile
  928. hero->play();
  929. }
  930. }