BattleAnimationClasses.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  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 <boost/math/constants/constants.hpp>
  13. #include "BattleInterfaceClasses.h"
  14. #include "BattleInterface.h"
  15. #include "BattleProjectileController.h"
  16. #include "BattleSiegeController.h"
  17. #include "BattleFieldController.h"
  18. #include "BattleEffectsController.h"
  19. #include "BattleStacksController.h"
  20. #include "CreatureAnimation.h"
  21. #include "../CGameInfo.h"
  22. #include "../CMusicHandler.h"
  23. #include "../CPlayerInterface.h"
  24. #include "../Graphics.h"
  25. #include "../gui/CAnimation.h"
  26. #include "../gui/CCursorHandler.h"
  27. #include "../gui/CGuiHandler.h"
  28. #include "../../CCallback.h"
  29. #include "../../lib/CStack.h"
  30. #include "../../lib/CTownHandler.h"
  31. #include "../../lib/mapObjects/CGTownInstance.h"
  32. CBattleAnimation::CBattleAnimation(BattleInterface & owner)
  33. : owner(owner),
  34. ID(owner.stacksController->animIDhelper++),
  35. initialized(false)
  36. {
  37. logAnim->trace("Animation #%d created", ID);
  38. }
  39. bool CBattleAnimation::tryInitialize()
  40. {
  41. assert(!initialized);
  42. if ( init() )
  43. {
  44. initialized = true;
  45. return true;
  46. }
  47. return false;
  48. }
  49. bool CBattleAnimation::isInitialized()
  50. {
  51. return initialized;
  52. }
  53. CBattleAnimation::~CBattleAnimation()
  54. {
  55. logAnim->trace("Animation #%d ended, type is %s", ID, typeid(this).name());
  56. for(auto & elem : pendingAnimations())
  57. {
  58. if(elem == this)
  59. elem = nullptr;
  60. }
  61. logAnim->trace("Animation #%d deleted", ID);
  62. }
  63. std::vector<CBattleAnimation *> & CBattleAnimation::pendingAnimations()
  64. {
  65. return owner.stacksController->currentAnimations;
  66. }
  67. std::shared_ptr<CreatureAnimation> CBattleAnimation::stackAnimation(const CStack * stack) const
  68. {
  69. return owner.stacksController->stackAnimation[stack->ID];
  70. }
  71. bool CBattleAnimation::stackFacingRight(const CStack * stack)
  72. {
  73. return owner.stacksController->stackFacingRight[stack->ID];
  74. }
  75. void CBattleAnimation::setStackFacingRight(const CStack * stack, bool facingRight)
  76. {
  77. owner.stacksController->stackFacingRight[stack->ID] = facingRight;
  78. }
  79. bool CBattleAnimation::checkInitialConditions()
  80. {
  81. int lowestMoveID = ID;
  82. auto * thAnim = dynamic_cast<CBattleStackAnimation *>(this);
  83. auto * thSen = dynamic_cast<CPointEffectAnimation *>(this);
  84. for(auto & elem : pendingAnimations())
  85. {
  86. auto * sen = dynamic_cast<CPointEffectAnimation *>(elem);
  87. // all effect animations can play concurrently with each other
  88. if(sen && thSen && sen != thSen)
  89. continue;
  90. auto * revAnim = dynamic_cast<CReverseAnimation *>(elem);
  91. // if there is high-priority reverse animation affecting our stack then this animation will wait
  92. if(revAnim && thAnim && revAnim && revAnim->stack->ID == thAnim->stack->ID && revAnim->priority)
  93. return false;
  94. if(elem)
  95. vstd::amin(lowestMoveID, elem->ID);
  96. }
  97. return ID == lowestMoveID;
  98. }
  99. CBattleStackAnimation::CBattleStackAnimation(BattleInterface & owner, const CStack * stack)
  100. : CBattleAnimation(owner),
  101. myAnim(stackAnimation(stack)),
  102. stack(stack)
  103. {
  104. assert(myAnim);
  105. }
  106. void CBattleStackAnimation::shiftColor(const ColorShifter * shifter)
  107. {
  108. assert(myAnim);
  109. myAnim->shiftColor(shifter);
  110. }
  111. void CAttackAnimation::nextFrame()
  112. {
  113. if(myAnim->getType() != group)
  114. {
  115. myAnim->setType(group);
  116. myAnim->onAnimationReset += [&](){ delete this; };
  117. }
  118. if(!soundPlayed)
  119. {
  120. if(shooting)
  121. CCS->soundh->playSound(battle_sound(getCreature(), shoot));
  122. else
  123. CCS->soundh->playSound(battle_sound(getCreature(), attack));
  124. soundPlayed = true;
  125. }
  126. }
  127. CAttackAnimation::~CAttackAnimation()
  128. {
  129. myAnim->setType(CCreatureAnim::HOLDING);
  130. }
  131. bool CAttackAnimation::checkInitialConditions()
  132. {
  133. for(auto & elem : pendingAnimations())
  134. {
  135. CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(elem);
  136. CReverseAnimation * revAnim = dynamic_cast<CReverseAnimation *>(stAnim);
  137. if(revAnim && attackedStack) // enemy must be fully reversed
  138. {
  139. if (revAnim->stack->ID == attackedStack->ID)
  140. return false;
  141. }
  142. }
  143. return CBattleAnimation::checkInitialConditions();
  144. }
  145. const CCreature * CAttackAnimation::getCreature() const
  146. {
  147. if (attackingStack->getCreature()->idNumber == CreatureID::ARROW_TOWERS)
  148. return owner.siegeController->getTurretCreature();
  149. else
  150. return attackingStack->getCreature();
  151. }
  152. CAttackAnimation::CAttackAnimation(BattleInterface & owner, const CStack *attacker, BattleHex _dest, const CStack *defender)
  153. : CBattleStackAnimation(owner, attacker),
  154. shooting(false),
  155. group(CCreatureAnim::SHOOT_FRONT),
  156. soundPlayed(false),
  157. dest(_dest),
  158. attackedStack(defender),
  159. attackingStack(attacker)
  160. {
  161. assert(attackingStack && "attackingStack is nullptr in CBattleAttack::CBattleAttack !\n");
  162. attackingStackPosBeforeReturn = attackingStack->getPosition();
  163. }
  164. CDefenceAnimation::CDefenceAnimation(StackAttackedInfo _attackedInfo, BattleInterface & owner)
  165. : CBattleStackAnimation(owner, _attackedInfo.defender),
  166. attacker(_attackedInfo.attacker),
  167. rangedAttack(_attackedInfo.indirectAttack),
  168. killed(_attackedInfo.killed),
  169. timeToWait(0)
  170. {
  171. logAnim->debug("Created defence anim for %s", _attackedInfo.defender->getName());
  172. }
  173. bool CDefenceAnimation::init()
  174. {
  175. ui32 lowestMoveID = ID;
  176. for(auto & elem : pendingAnimations())
  177. {
  178. auto * defAnim = dynamic_cast<CDefenceAnimation *>(elem);
  179. if(defAnim && defAnim->stack->ID != stack->ID)
  180. continue;
  181. auto * attAnim = dynamic_cast<CAttackAnimation *>(elem);
  182. if(attAnim && attAnim->stack->ID != stack->ID)
  183. continue;
  184. auto * sen = dynamic_cast<CPointEffectAnimation *>(elem);
  185. if (sen && attacker == nullptr)
  186. return false;
  187. if (sen)
  188. continue;
  189. CReverseAnimation * animAsRev = dynamic_cast<CReverseAnimation *>(elem);
  190. if(animAsRev)
  191. return false;
  192. if(elem)
  193. vstd::amin(lowestMoveID, elem->ID);
  194. }
  195. if(ID > lowestMoveID)
  196. return false;
  197. //reverse unit if necessary
  198. if(attacker && owner.getCurrentPlayerInterface()->cb->isToReverse(stack->getPosition(), attacker->getPosition(), stackFacingRight(stack), attacker->doubleWide(), stackFacingRight(attacker)))
  199. {
  200. owner.stacksController->addNewAnim(new CReverseAnimation(owner, stack, stack->getPosition(), true));
  201. return false;
  202. }
  203. //unit reversed
  204. if(rangedAttack && attacker != nullptr && owner.projectilesController->hasActiveProjectile(attacker)) //delay hit animation
  205. {
  206. return false;
  207. }
  208. // synchronize animation with attacker, unless defending or attacked by shooter:
  209. // wait for 1/2 of attack animation
  210. if (!rangedAttack && getMyAnimType() != CCreatureAnim::DEFENCE)
  211. {
  212. float frameLength = AnimationControls::getCreatureAnimationSpeed(
  213. stack->getCreature(), stackAnimation(stack).get(), getMyAnimType());
  214. timeToWait = myAnim->framesInGroup(getMyAnimType()) * frameLength / 2;
  215. myAnim->setType(CCreatureAnim::HOLDING);
  216. }
  217. else
  218. {
  219. timeToWait = 0;
  220. startAnimation();
  221. }
  222. return true; //initialized successfuly
  223. }
  224. std::string CDefenceAnimation::getMySound()
  225. {
  226. if(killed)
  227. return battle_sound(stack->getCreature(), killed);
  228. else if(stack->defendingAnim)
  229. return battle_sound(stack->getCreature(), defend);
  230. else
  231. return battle_sound(stack->getCreature(), wince);
  232. }
  233. CCreatureAnim::EAnimType CDefenceAnimation::getMyAnimType()
  234. {
  235. if(killed)
  236. {
  237. if(rangedAttack && myAnim->framesInGroup(CCreatureAnim::DEATH_RANGED) > 0)
  238. return CCreatureAnim::DEATH_RANGED;
  239. else
  240. return CCreatureAnim::DEATH;
  241. }
  242. if(stack->defendingAnim)
  243. return CCreatureAnim::DEFENCE;
  244. else
  245. return CCreatureAnim::HITTED;
  246. }
  247. void CDefenceAnimation::startAnimation()
  248. {
  249. CCS->soundh->playSound(getMySound());
  250. myAnim->setType(getMyAnimType());
  251. myAnim->onAnimationReset += [&](){ delete this; };
  252. }
  253. void CDefenceAnimation::nextFrame()
  254. {
  255. if (timeToWait > 0)
  256. {
  257. timeToWait -= float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000;
  258. if (timeToWait <= 0)
  259. startAnimation();
  260. }
  261. CBattleAnimation::nextFrame();
  262. }
  263. CDefenceAnimation::~CDefenceAnimation()
  264. {
  265. if(killed)
  266. {
  267. if(rangedAttack && myAnim->framesInGroup(CCreatureAnim::DEAD_RANGED) > 0)
  268. myAnim->setType(CCreatureAnim::DEAD_RANGED);
  269. else
  270. myAnim->setType(CCreatureAnim::DEAD);
  271. }
  272. else
  273. {
  274. myAnim->setType(CCreatureAnim::HOLDING);
  275. }
  276. }
  277. CDummyAnimation::CDummyAnimation(BattleInterface & owner, int howManyFrames)
  278. : CBattleAnimation(owner),
  279. counter(0),
  280. howMany(howManyFrames)
  281. {
  282. logAnim->debug("Created dummy animation for %d frames", howManyFrames);
  283. }
  284. bool CDummyAnimation::init()
  285. {
  286. return true;
  287. }
  288. void CDummyAnimation::nextFrame()
  289. {
  290. counter++;
  291. if(counter > howMany)
  292. delete this;
  293. }
  294. bool CMeleeAttackAnimation::init()
  295. {
  296. if(!CAttackAnimation::checkInitialConditions())
  297. return false;
  298. if(!attackingStack || myAnim->isDeadOrDying())
  299. {
  300. delete this;
  301. return false;
  302. }
  303. bool toReverse = owner.getCurrentPlayerInterface()->cb->isToReverse(attackingStackPosBeforeReturn, attackedStack->getPosition(), stackFacingRight(stack), attackedStack->doubleWide(), stackFacingRight(attackedStack));
  304. if(toReverse)
  305. {
  306. owner.stacksController->addNewAnim(new CReverseAnimation(owner, stack, attackingStackPosBeforeReturn, true));
  307. return false;
  308. }
  309. // opponent must face attacker ( = different directions) before he can be attacked
  310. if(attackingStack && attackedStack &&
  311. stackFacingRight(attackingStack) == stackFacingRight(attackedStack))
  312. return false;
  313. //reversed
  314. shooting = false;
  315. static const CCreatureAnim::EAnimType mutPosToGroup[] =
  316. {
  317. CCreatureAnim::ATTACK_UP,
  318. CCreatureAnim::ATTACK_UP,
  319. CCreatureAnim::ATTACK_FRONT,
  320. CCreatureAnim::ATTACK_DOWN,
  321. CCreatureAnim::ATTACK_DOWN,
  322. CCreatureAnim::ATTACK_FRONT
  323. };
  324. static const CCreatureAnim::EAnimType mutPosToGroup2H[] =
  325. {
  326. CCreatureAnim::VCMI_2HEX_UP,
  327. CCreatureAnim::VCMI_2HEX_UP,
  328. CCreatureAnim::VCMI_2HEX_FRONT,
  329. CCreatureAnim::VCMI_2HEX_DOWN,
  330. CCreatureAnim::VCMI_2HEX_DOWN,
  331. CCreatureAnim::VCMI_2HEX_FRONT
  332. };
  333. int revShiftattacker = (attackingStack->side == BattleSide::ATTACKER ? -1 : 1);
  334. int mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, dest);
  335. if(mutPos == -1 && attackingStack->doubleWide())
  336. {
  337. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->getPosition());
  338. }
  339. if (mutPos == -1 && attackedStack->doubleWide())
  340. {
  341. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, attackedStack->occupiedHex());
  342. }
  343. if (mutPos == -1 && attackedStack->doubleWide() && attackingStack->doubleWide())
  344. {
  345. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->occupiedHex());
  346. }
  347. switch(mutPos) //attack direction
  348. {
  349. case 0:
  350. case 1:
  351. case 2:
  352. case 3:
  353. case 4:
  354. case 5:
  355. group = mutPosToGroup[mutPos];
  356. if(attackingStack->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
  357. {
  358. CCreatureAnim::EAnimType group2H = mutPosToGroup2H[mutPos];
  359. if(myAnim->framesInGroup(group2H)>0)
  360. group = group2H;
  361. }
  362. break;
  363. default:
  364. logGlobal->error("Critical Error! Wrong dest in stackAttacking! dest: %d; attacking stack pos: %d; mutual pos: %d", dest.hex, attackingStackPosBeforeReturn, mutPos);
  365. group = CCreatureAnim::ATTACK_FRONT;
  366. break;
  367. }
  368. return true;
  369. }
  370. CMeleeAttackAnimation::CMeleeAttackAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
  371. : CAttackAnimation(owner, attacker, _dest, _attacked)
  372. {
  373. logAnim->debug("Created melee attack anim for %s", attacker->getName());
  374. }
  375. CStackMoveAnimation::CStackMoveAnimation(BattleInterface & owner, const CStack * _stack, BattleHex _currentHex):
  376. CBattleStackAnimation(owner, _stack),
  377. currentHex(_currentHex)
  378. {
  379. }
  380. bool CMovementAnimation::init()
  381. {
  382. if( !CBattleAnimation::checkInitialConditions() )
  383. return false;
  384. if(!stack || myAnim->isDeadOrDying())
  385. {
  386. delete this;
  387. return false;
  388. }
  389. if(stackAnimation(stack)->framesInGroup(CCreatureAnim::MOVING) == 0 ||
  390. stack->hasBonus(Selector::typeSubtype(Bonus::FLYING, 1)))
  391. {
  392. //no movement or teleport, end immediately
  393. delete this;
  394. return false;
  395. }
  396. //reverse unit if necessary
  397. if(owner.stacksController->shouldRotate(stack, oldPos, currentHex))
  398. {
  399. // it seems that H3 does NOT plays full rotation animation here in most situations
  400. // Logical since it takes quite a lot of time
  401. if (curentMoveIndex == 0) // full rotation only for moving towards first tile.
  402. {
  403. owner.stacksController->addNewAnim(new CReverseAnimation(owner, stack, oldPos, true));
  404. return false;
  405. }
  406. else
  407. {
  408. rotateStack(oldPos);
  409. }
  410. }
  411. if(myAnim->getType() != CCreatureAnim::MOVING)
  412. {
  413. myAnim->setType(CCreatureAnim::MOVING);
  414. }
  415. if (owner.moveSoundHander == -1)
  416. {
  417. owner.moveSoundHander = CCS->soundh->playSound(battle_sound(stack->getCreature(), move), -1);
  418. }
  419. Point begPosition = owner.stacksController->getStackPositionAtHex(oldPos, stack);
  420. Point endPosition = owner.stacksController->getStackPositionAtHex(currentHex, stack);
  421. timeToMove = AnimationControls::getMovementDuration(stack->getCreature());
  422. begX = begPosition.x;
  423. begY = begPosition.y;
  424. progress = 0;
  425. distanceX = endPosition.x - begPosition.x;
  426. distanceY = endPosition.y - begPosition.y;
  427. if (stack->hasBonus(Selector::type()(Bonus::FLYING)))
  428. {
  429. float distance = static_cast<float>(sqrt(distanceX * distanceX + distanceY * distanceY));
  430. timeToMove *= AnimationControls::getFlightDistance(stack->getCreature()) / distance;
  431. }
  432. return true;
  433. }
  434. void CMovementAnimation::nextFrame()
  435. {
  436. progress += float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000 * timeToMove;
  437. //moving instructions
  438. myAnim->pos.x = static_cast<Sint16>(begX + distanceX * progress );
  439. myAnim->pos.y = static_cast<Sint16>(begY + distanceY * progress );
  440. CBattleAnimation::nextFrame();
  441. if(progress >= 1.0)
  442. {
  443. // Sets the position of the creature animation sprites
  444. Point coords = owner.stacksController->getStackPositionAtHex(currentHex, stack);
  445. myAnim->pos = coords;
  446. // true if creature haven't reached the final destination hex
  447. if ((curentMoveIndex + 1) < destTiles.size())
  448. {
  449. // update the next hex field which has to be reached by the stack
  450. curentMoveIndex++;
  451. oldPos = currentHex;
  452. currentHex = destTiles[curentMoveIndex];
  453. // request re-initialization
  454. initialized = false;
  455. }
  456. else
  457. delete this;
  458. }
  459. }
  460. CMovementAnimation::~CMovementAnimation()
  461. {
  462. assert(stack);
  463. myAnim->pos = owner.stacksController->getStackPositionAtHex(currentHex, stack);
  464. owner.stacksController->addNewAnim(new CMovementEndAnimation(owner, stack, currentHex));
  465. if(owner.moveSoundHander != -1)
  466. {
  467. CCS->soundh->stopSound(owner.moveSoundHander);
  468. owner.moveSoundHander = -1;
  469. }
  470. }
  471. CMovementAnimation::CMovementAnimation(BattleInterface & owner, const CStack *_stack, std::vector<BattleHex> _destTiles, int _distance)
  472. : CStackMoveAnimation(owner, _stack, _destTiles.front()),
  473. destTiles(_destTiles),
  474. curentMoveIndex(0),
  475. oldPos(stack->getPosition()),
  476. begX(0), begY(0),
  477. distanceX(0), distanceY(0),
  478. timeToMove(0.0),
  479. progress(0.0)
  480. {
  481. logAnim->debug("Created movement anim for %s", stack->getName());
  482. }
  483. CMovementEndAnimation::CMovementEndAnimation(BattleInterface & owner, const CStack * _stack, BattleHex destTile)
  484. : CStackMoveAnimation(owner, _stack, destTile)
  485. {
  486. logAnim->debug("Created movement end anim for %s", stack->getName());
  487. }
  488. bool CMovementEndAnimation::init()
  489. {
  490. //if( !isEarliest(true) )
  491. // return false;
  492. if(!stack || myAnim->framesInGroup(CCreatureAnim::MOVE_END) == 0 ||
  493. myAnim->isDeadOrDying())
  494. {
  495. delete this;
  496. return false;
  497. }
  498. CCS->soundh->playSound(battle_sound(stack->getCreature(), endMoving));
  499. myAnim->setType(CCreatureAnim::MOVE_END);
  500. myAnim->onAnimationReset += [&](){ delete this; };
  501. return true;
  502. }
  503. CMovementEndAnimation::~CMovementEndAnimation()
  504. {
  505. if(myAnim->getType() != CCreatureAnim::DEAD)
  506. myAnim->setType(CCreatureAnim::HOLDING); //resetting to default
  507. CCS->curh->show();
  508. }
  509. CMovementStartAnimation::CMovementStartAnimation(BattleInterface & owner, const CStack * _stack)
  510. : CStackMoveAnimation(owner, _stack, _stack->getPosition())
  511. {
  512. logAnim->debug("Created movement start anim for %s", stack->getName());
  513. }
  514. bool CMovementStartAnimation::init()
  515. {
  516. if( !CBattleAnimation::checkInitialConditions() )
  517. return false;
  518. if(!stack || myAnim->isDeadOrDying())
  519. {
  520. delete this;
  521. return false;
  522. }
  523. CCS->soundh->playSound(battle_sound(stack->getCreature(), startMoving));
  524. myAnim->setType(CCreatureAnim::MOVE_START);
  525. myAnim->onAnimationReset += [&](){ delete this; };
  526. return true;
  527. }
  528. CReverseAnimation::CReverseAnimation(BattleInterface & owner, const CStack * stack, BattleHex dest, bool _priority)
  529. : CStackMoveAnimation(owner, stack, dest),
  530. priority(_priority)
  531. {
  532. logAnim->debug("Created reverse anim for %s", stack->getName());
  533. }
  534. bool CReverseAnimation::init()
  535. {
  536. if(myAnim == nullptr || myAnim->isDeadOrDying())
  537. {
  538. delete this;
  539. return false; //there is no such creature
  540. }
  541. if(!priority && !CBattleAnimation::checkInitialConditions())
  542. return false;
  543. if(myAnim->framesInGroup(CCreatureAnim::TURN_L))
  544. {
  545. myAnim->setType(CCreatureAnim::TURN_L);
  546. myAnim->onAnimationReset += std::bind(&CReverseAnimation::setupSecondPart, this);
  547. }
  548. else
  549. {
  550. setupSecondPart();
  551. }
  552. return true;
  553. }
  554. CReverseAnimation::~CReverseAnimation()
  555. {
  556. if( stack && stack->alive() )//don't do that if stack is dead
  557. myAnim->setType(CCreatureAnim::HOLDING);
  558. }
  559. void CBattleStackAnimation::rotateStack(BattleHex hex)
  560. {
  561. setStackFacingRight(stack, !stackFacingRight(stack));
  562. stackAnimation(stack)->pos = owner.stacksController->getStackPositionAtHex(hex, stack);
  563. }
  564. void CReverseAnimation::setupSecondPart()
  565. {
  566. if(!stack)
  567. {
  568. delete this;
  569. return;
  570. }
  571. rotateStack(currentHex);
  572. if(myAnim->framesInGroup(CCreatureAnim::TURN_R))
  573. {
  574. myAnim->setType(CCreatureAnim::TURN_R);
  575. myAnim->onAnimationReset += [&](){ delete this; };
  576. }
  577. else
  578. delete this;
  579. }
  580. CRangedAttackAnimation::CRangedAttackAnimation(BattleInterface & owner, const CStack * attacker, BattleHex dest_, const CStack * defender)
  581. : CAttackAnimation(owner, attacker, dest_, defender),
  582. projectileEmitted(false)
  583. {
  584. logAnim->info("Ranged attack animation created");
  585. }
  586. bool CRangedAttackAnimation::init()
  587. {
  588. if( !CAttackAnimation::checkInitialConditions() )
  589. return false;
  590. assert(attackingStack);
  591. assert(!myAnim->isDeadOrDying());
  592. if(!attackingStack || myAnim->isDeadOrDying())
  593. {
  594. //FIXME: how is this possible?
  595. logAnim->warn("Shooting animation has not started yet but attacker is dead! Aborting...");
  596. delete this;
  597. return false;
  598. }
  599. //reverse unit if necessary
  600. if (attackingStack && attackedStack && owner.getCurrentPlayerInterface()->cb->isToReverse(attackingStack->getPosition(), attackedStack->getPosition(), stackFacingRight(attackingStack), attackingStack->doubleWide(), stackFacingRight(attackedStack)))
  601. {
  602. owner.stacksController->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->getPosition(), true));
  603. return false;
  604. }
  605. logAnim->info("Ranged attack animation initialized");
  606. setAnimationGroup();
  607. initializeProjectile();
  608. shooting = true;
  609. return true;
  610. }
  611. void CRangedAttackAnimation::setAnimationGroup()
  612. {
  613. Point shooterPos = stackAnimation(attackingStack)->pos.topLeft();
  614. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, attackedStack);
  615. //maximal angle in radians between straight horizontal line and shooting line for which shot is considered to be straight (absoulte value)
  616. static const double straightAngle = 0.2;
  617. double projectileAngle = -atan2(shotTarget.y - shooterPos.y, std::abs(shotTarget.x - shooterPos.x));
  618. // Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
  619. if (projectileAngle > straightAngle)
  620. group = getUpwardsGroup();
  621. else if (projectileAngle < -straightAngle)
  622. group = getDownwardsGroup();
  623. else
  624. group = getForwardGroup();
  625. }
  626. void CRangedAttackAnimation::initializeProjectile()
  627. {
  628. const CCreature *shooterInfo = getCreature();
  629. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, attackedStack) + Point(225, 225);
  630. Point shotOrigin = stackAnimation(attackingStack)->pos.topLeft() + Point(222, 265);
  631. int multiplier = stackFacingRight(attackingStack) ? 1 : -1;
  632. if (group == getUpwardsGroup())
  633. {
  634. shotOrigin.x += ( -25 + shooterInfo->animation.upperRightMissleOffsetX ) * multiplier;
  635. shotOrigin.y += shooterInfo->animation.upperRightMissleOffsetY;
  636. }
  637. else if (group == getDownwardsGroup())
  638. {
  639. shotOrigin.x += ( -25 + shooterInfo->animation.lowerRightMissleOffsetX ) * multiplier;
  640. shotOrigin.y += shooterInfo->animation.lowerRightMissleOffsetY;
  641. }
  642. else if (group == getForwardGroup())
  643. {
  644. shotOrigin.x += ( -25 + shooterInfo->animation.rightMissleOffsetX ) * multiplier;
  645. shotOrigin.y += shooterInfo->animation.rightMissleOffsetY;
  646. }
  647. else
  648. {
  649. assert(0);
  650. }
  651. createProjectile(shotOrigin, shotTarget);
  652. }
  653. void CRangedAttackAnimation::emitProjectile()
  654. {
  655. logAnim->info("Ranged attack projectile emitted");
  656. owner.projectilesController->emitStackProjectile(attackingStack);
  657. projectileEmitted = true;
  658. }
  659. void CRangedAttackAnimation::nextFrame()
  660. {
  661. for(auto & it : pendingAnimations())
  662. {
  663. CMovementStartAnimation * anim = dynamic_cast<CMovementStartAnimation *>(it);
  664. CReverseAnimation * anim2 = dynamic_cast<CReverseAnimation *>(it);
  665. if( (anim && anim->stack->ID == stack->ID) || (anim2 && anim2->stack->ID == stack->ID && anim2->priority ) )
  666. {
  667. assert(0); // FIXME: our stack started to move even though we are playing shooting animation? How?
  668. return;
  669. }
  670. }
  671. // animation should be paused if there is an active projectile
  672. if (projectileEmitted)
  673. {
  674. if (owner.projectilesController->hasActiveProjectile(attackingStack))
  675. stackAnimation(attackingStack)->pause();
  676. else
  677. stackAnimation(attackingStack)->play();
  678. }
  679. CAttackAnimation::nextFrame();
  680. if (!projectileEmitted)
  681. {
  682. logAnim->info("Ranged attack executing, %d / %d / %d",
  683. stackAnimation(attackingStack)->getCurrentFrame(),
  684. getAttackClimaxFrame(),
  685. stackAnimation(attackingStack)->framesInGroup(group));
  686. // emit projectile once animation playback reached "climax" frame
  687. if ( stackAnimation(attackingStack)->getCurrentFrame() >= getAttackClimaxFrame() )
  688. {
  689. emitProjectile();
  690. stackAnimation(attackingStack)->pause();
  691. return;
  692. }
  693. }
  694. }
  695. CRangedAttackAnimation::~CRangedAttackAnimation()
  696. {
  697. logAnim->info("Ranged attack animation is over");
  698. //FIXME: this assert triggers under some unclear, rare conditions. Possibly - if game window is inactive and/or in foreground/minimized?
  699. assert(!owner.projectilesController->hasActiveProjectile(attackingStack));
  700. assert(projectileEmitted);
  701. // FIXME: is this possible? Animation is over but we're yet to fire projectile?
  702. if (!projectileEmitted)
  703. {
  704. logAnim->warn("Shooting animation has finished but projectile was not emitted! Emitting it now...");
  705. emitProjectile();
  706. }
  707. }
  708. CShootingAnimation::CShootingAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
  709. : CRangedAttackAnimation(owner, attacker, _dest, _attacked)
  710. {
  711. logAnim->debug("Created shooting anim for %s", stack->getName());
  712. }
  713. void CShootingAnimation::createProjectile(const Point & from, const Point & dest) const
  714. {
  715. owner.projectilesController->createProjectile(attackingStack, from, dest);
  716. }
  717. uint32_t CShootingAnimation::getAttackClimaxFrame() const
  718. {
  719. const CCreature *shooterInfo = getCreature();
  720. return shooterInfo->animation.attackClimaxFrame;
  721. }
  722. CCreatureAnim::EAnimType CShootingAnimation::getUpwardsGroup() const
  723. {
  724. return CCreatureAnim::SHOOT_UP;
  725. }
  726. CCreatureAnim::EAnimType CShootingAnimation::getForwardGroup() const
  727. {
  728. return CCreatureAnim::SHOOT_FRONT;
  729. }
  730. CCreatureAnim::EAnimType CShootingAnimation::getDownwardsGroup() const
  731. {
  732. return CCreatureAnim::SHOOT_DOWN;
  733. }
  734. CCatapultAnimation::CCatapultAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, int _catapultDmg)
  735. : CShootingAnimation(owner, attacker, _dest, _attacked),
  736. catapultDamage(_catapultDmg),
  737. explosionEmitted(false)
  738. {
  739. logAnim->debug("Created shooting anim for %s", stack->getName());
  740. }
  741. void CCatapultAnimation::nextFrame()
  742. {
  743. CShootingAnimation::nextFrame();
  744. if ( explosionEmitted)
  745. return;
  746. if ( !projectileEmitted)
  747. return;
  748. if (owner.projectilesController->hasActiveProjectile(attackingStack))
  749. return;
  750. explosionEmitted = true;
  751. Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, attackedStack) + Point(225, 225) - Point(126, 105);
  752. if(catapultDamage > 0)
  753. owner.stacksController->addNewAnim( new CPointEffectAnimation(owner, soundBase::WALLHIT, "SGEXPL.DEF", shotTarget));
  754. else
  755. owner.stacksController->addNewAnim( new CPointEffectAnimation(owner, soundBase::WALLMISS, "CSGRCK.DEF", shotTarget));
  756. }
  757. void CCatapultAnimation::createProjectile(const Point & from, const Point & dest) const
  758. {
  759. owner.projectilesController->createCatapultProjectile(attackingStack, from, dest);
  760. }
  761. CCastAnimation::CCastAnimation(BattleInterface & owner, const CStack * attacker, BattleHex dest_, const CStack * defender, const CSpell * spell)
  762. : CRangedAttackAnimation(owner, attacker, dest_, defender),
  763. spell(spell)
  764. {
  765. assert(dest.isValid());// FIXME: when?
  766. if(!dest_.isValid() && defender)
  767. dest = defender->getPosition();
  768. }
  769. CCreatureAnim::EAnimType CCastAnimation::findValidGroup( const std::vector<CCreatureAnim::EAnimType> candidates ) const
  770. {
  771. for ( auto group : candidates)
  772. {
  773. if(myAnim->framesInGroup(group) > 0)
  774. return group;
  775. }
  776. assert(0);
  777. return CCreatureAnim::HOLDING;
  778. }
  779. CCreatureAnim::EAnimType CCastAnimation::getUpwardsGroup() const
  780. {
  781. return findValidGroup({
  782. CCreatureAnim::VCMI_CAST_UP,
  783. CCreatureAnim::CAST_UP,
  784. CCreatureAnim::SHOOT_UP,
  785. CCreatureAnim::ATTACK_UP
  786. });
  787. }
  788. CCreatureAnim::EAnimType CCastAnimation::getForwardGroup() const
  789. {
  790. return findValidGroup({
  791. CCreatureAnim::VCMI_CAST_FRONT,
  792. CCreatureAnim::CAST_FRONT,
  793. CCreatureAnim::SHOOT_FRONT,
  794. CCreatureAnim::ATTACK_FRONT
  795. });
  796. }
  797. CCreatureAnim::EAnimType CCastAnimation::getDownwardsGroup() const
  798. {
  799. return findValidGroup({
  800. CCreatureAnim::VCMI_CAST_DOWN,
  801. CCreatureAnim::CAST_DOWN,
  802. CCreatureAnim::SHOOT_DOWN,
  803. CCreatureAnim::ATTACK_DOWN
  804. });
  805. }
  806. void CCastAnimation::createProjectile(const Point & from, const Point & dest) const
  807. {
  808. if (!spell->animationInfo.projectile.empty())
  809. owner.projectilesController->createSpellProjectile(attackingStack, from, dest, spell);
  810. }
  811. uint32_t CCastAnimation::getAttackClimaxFrame() const
  812. {
  813. //FIXME: allow defining this parameter in config file, separately from attackClimaxFrame of missile attacks
  814. uint32_t maxFrames = stackAnimation(attackingStack)->framesInGroup(group);
  815. if (maxFrames > 2)
  816. return maxFrames - 2;
  817. return 0;
  818. }
  819. CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, int effects):
  820. CBattleAnimation(owner),
  821. animation(std::make_shared<CAnimation>(animationName)),
  822. sound(sound),
  823. effectFlags(effects),
  824. soundPlayed(false),
  825. soundFinished(false),
  826. effectFinished(false)
  827. {
  828. }
  829. CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, std::vector<BattleHex> hex, int effects):
  830. CPointEffectAnimation(owner, sound, animationName, effects)
  831. {
  832. battlehexes = hex;
  833. }
  834. CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, BattleHex hex, int effects):
  835. CPointEffectAnimation(owner, sound, animationName, effects)
  836. {
  837. assert(hex.isValid());
  838. battlehexes.push_back(hex);
  839. }
  840. CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, std::vector<Point> pos, int effects):
  841. CPointEffectAnimation(owner, sound, animationName, effects)
  842. {
  843. positions = pos;
  844. }
  845. CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, Point pos, int effects):
  846. CPointEffectAnimation(owner, sound, animationName, effects)
  847. {
  848. positions.push_back(pos);
  849. }
  850. CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, Point pos, BattleHex hex, int effects):
  851. CPointEffectAnimation(owner, sound, animationName, effects)
  852. {
  853. assert(hex.isValid());
  854. battlehexes.push_back(hex);
  855. positions.push_back(pos);
  856. }
  857. bool CPointEffectAnimation::init()
  858. {
  859. if(!CBattleAnimation::checkInitialConditions())
  860. return false;
  861. animation->preload();
  862. auto first = animation->getImage(0, 0, true);
  863. if(!first)
  864. {
  865. delete this;
  866. return false;
  867. }
  868. if (screenFill())
  869. {
  870. for(int i=0; i * first->width() < owner.pos.w ; ++i)
  871. for(int j=0; j * first->height() < owner.pos.h ; ++j)
  872. positions.push_back(Point( owner.pos.x + i * first->width(), owner.pos.y + j * first->height()));
  873. }
  874. BattleEffect be;
  875. be.effectID = ID;
  876. be.animation = animation;
  877. be.currentFrame = 0;
  878. for (size_t i = 0; i < std::max(battlehexes.size(), positions.size()); ++i)
  879. {
  880. bool hasTile = i < battlehexes.size();
  881. bool hasPosition = i < positions.size();
  882. if (hasTile && !forceOnTop())
  883. be.position = battlehexes[i];
  884. else
  885. be.position = BattleHex::INVALID;
  886. if (hasPosition)
  887. {
  888. be.x = positions[i].x;
  889. be.y = positions[i].y;
  890. }
  891. else
  892. {
  893. const CStack * destStack = owner.getCurrentPlayerInterface()->cb->battleGetStackByPos(battlehexes[i], false);
  894. Rect tilePos = owner.fieldController->hexPositionAbsolute(battlehexes[i]);
  895. be.x = tilePos.x + tilePos.w/2 - first->width()/2;
  896. if(destStack && destStack->doubleWide()) // Correction for 2-hex creatures.
  897. be.x += (destStack->side == BattleSide::ATTACKER ? -1 : 1)*tilePos.w/2;
  898. if (alignToBottom())
  899. be.y = tilePos.y + tilePos.h - first->height();
  900. else
  901. be.y = tilePos.y - first->height()/2;
  902. }
  903. owner.effectsController->battleEffects.push_back(be);
  904. }
  905. return true;
  906. }
  907. void CPointEffectAnimation::nextFrame()
  908. {
  909. playSound();
  910. playEffect();
  911. if (soundFinished && effectFinished)
  912. {
  913. //remove visual effect itself only if sound has finished as well - necessary for obstacles like force field
  914. clearEffect();
  915. delete this;
  916. }
  917. }
  918. bool CPointEffectAnimation::alignToBottom() const
  919. {
  920. return effectFlags & ALIGN_TO_BOTTOM;
  921. }
  922. bool CPointEffectAnimation::waitForSound() const
  923. {
  924. return effectFlags & WAIT_FOR_SOUND;
  925. }
  926. bool CPointEffectAnimation::forceOnTop() const
  927. {
  928. return effectFlags & FORCE_ON_TOP;
  929. }
  930. bool CPointEffectAnimation::screenFill() const
  931. {
  932. return effectFlags & SCREEN_FILL;
  933. }
  934. void CPointEffectAnimation::onEffectFinished()
  935. {
  936. effectFinished = true;
  937. }
  938. void CPointEffectAnimation::onSoundFinished()
  939. {
  940. soundFinished = true;
  941. }
  942. void CPointEffectAnimation::playSound()
  943. {
  944. if (soundPlayed)
  945. return;
  946. soundPlayed = true;
  947. if (sound == soundBase::invalid)
  948. {
  949. onSoundFinished();
  950. return;
  951. }
  952. int channel = CCS->soundh->playSound(sound);
  953. if (!waitForSound() || channel == -1)
  954. onSoundFinished();
  955. else
  956. CCS->soundh->setCallback(channel, [&](){ onSoundFinished(); });
  957. }
  958. void CPointEffectAnimation::playEffect()
  959. {
  960. if ( effectFinished )
  961. return;
  962. for(auto & elem : owner.effectsController->battleEffects)
  963. {
  964. if(elem.effectID == ID)
  965. {
  966. elem.currentFrame += AnimationControls::getSpellEffectSpeed() * GH.mainFPSmng->getElapsedMilliseconds() / 1000;
  967. if(elem.currentFrame >= elem.animation->size())
  968. {
  969. elem.currentFrame = elem.animation->size() - 1;
  970. onEffectFinished();
  971. break;
  972. }
  973. }
  974. }
  975. }
  976. void CPointEffectAnimation::clearEffect()
  977. {
  978. auto & effects = owner.effectsController->battleEffects;
  979. vstd::erase_if(effects, [&](const BattleEffect & effect){
  980. return effect.effectID == ID;
  981. });
  982. }
  983. CPointEffectAnimation::~CPointEffectAnimation()
  984. {
  985. assert(effectFinished);
  986. assert(soundFinished);
  987. }
  988. CWaitingAnimation::CWaitingAnimation(BattleInterface & owner):
  989. CBattleAnimation(owner)
  990. {}
  991. void CWaitingAnimation::nextFrame()
  992. {
  993. // initialization conditions fulfilled, delay is over
  994. delete this;
  995. }
  996. CWaitingProjectileAnimation::CWaitingProjectileAnimation(BattleInterface & owner, const CStack * shooter):
  997. CWaitingAnimation(owner),
  998. shooter(shooter)
  999. {}
  1000. bool CWaitingProjectileAnimation::init()
  1001. {
  1002. for(auto & elem : pendingAnimations())
  1003. {
  1004. auto * attackAnim = dynamic_cast<CRangedAttackAnimation *>(elem);
  1005. if( attackAnim && shooter && attackAnim->stack->ID == shooter->ID && !attackAnim->isInitialized() )
  1006. {
  1007. // there is ongoing ranged attack that involves our stack, but projectile was not created yet
  1008. return false;
  1009. }
  1010. }
  1011. if(owner.projectilesController->hasActiveProjectile(shooter))
  1012. return false;
  1013. return true;
  1014. }