CBattleAnimations.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  1. /*
  2. * CBattleAnimations.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 "CBattleAnimations.h"
  12. #include <boost/math/constants/constants.hpp>
  13. #include "CBattleInterfaceClasses.h"
  14. #include "CBattleInterface.h"
  15. #include "CBattleProjectileController.h"
  16. #include "CBattleSiegeController.h"
  17. #include "CBattleFieldController.h"
  18. #include "CBattleEffectsController.h"
  19. #include "CBattleStacksController.h"
  20. #include "CCreatureAnimation.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(CBattleInterface * _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<CCreatureAnimation> CBattleAnimation::stackAnimation(const CStack * stack)
  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(CBattleInterface * 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()
  146. {
  147. if (attackingStack->getCreature()->idNumber == CreatureID::ARROW_TOWERS)
  148. return owner->siegeController->getTurretCreature();
  149. else
  150. return attackingStack->getCreature();
  151. }
  152. CAttackAnimation::CAttackAnimation(CBattleInterface *_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, CBattleInterface * _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(CBattleInterface * _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(CBattleInterface * _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(CBattleInterface * _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(CBattleInterface *_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(CBattleInterface * _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(CBattleInterface * _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(CBattleInterface * _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(CBattleInterface * 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. const CCreature *shooterInfo = getCreature();
  683. logAnim->info("Ranged attack executing, %d / %d / %d",
  684. stackAnimation(attackingStack)->getCurrentFrame(),
  685. shooterInfo->animation.attackClimaxFrame,
  686. stackAnimation(attackingStack)->framesInGroup(group));
  687. // emit projectile once animation playback reached "climax" frame
  688. if ( stackAnimation(attackingStack)->getCurrentFrame() >= shooterInfo->animation.attackClimaxFrame )
  689. {
  690. emitProjectile();
  691. stackAnimation(attackingStack)->pause();
  692. return;
  693. }
  694. }
  695. }
  696. CRangedAttackAnimation::~CRangedAttackAnimation()
  697. {
  698. logAnim->info("Ranged attack animation is over");
  699. //FIXME: this assert triggers under some unclear, rare conditions. Possibly - if game window is inactive and/or in foreground/minimized?
  700. assert(!owner->projectilesController->hasActiveProjectile(attackingStack));
  701. assert(projectileEmitted);
  702. // FIXME: is this possible? Animation is over but we're yet to fire projectile?
  703. if (!projectileEmitted)
  704. {
  705. logAnim->warn("Shooting animation has finished but projectile was not emitted! Emitting it now...");
  706. emitProjectile();
  707. }
  708. }
  709. CShootingAnimation::CShootingAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
  710. : CRangedAttackAnimation(_owner, attacker, _dest, _attacked)
  711. {
  712. logAnim->debug("Created shooting anim for %s", stack->getName());
  713. }
  714. void CShootingAnimation::createProjectile(const Point & from, const Point & dest) const
  715. {
  716. owner->projectilesController->createProjectile(attackingStack, attackedStack, from, dest);
  717. }
  718. CCreatureAnim::EAnimType CShootingAnimation::getUpwardsGroup() const
  719. {
  720. return CCreatureAnim::SHOOT_UP;
  721. }
  722. CCreatureAnim::EAnimType CShootingAnimation::getForwardGroup() const
  723. {
  724. return CCreatureAnim::SHOOT_FRONT;
  725. }
  726. CCreatureAnim::EAnimType CShootingAnimation::getDownwardsGroup() const
  727. {
  728. return CCreatureAnim::SHOOT_DOWN;
  729. }
  730. CCatapultAnimation::CCatapultAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, int _catapultDmg)
  731. : CShootingAnimation(_owner, attacker, _dest, _attacked),
  732. catapultDamage(_catapultDmg),
  733. explosionEmitted(false)
  734. {
  735. logAnim->debug("Created shooting anim for %s", stack->getName());
  736. }
  737. void CCatapultAnimation::nextFrame()
  738. {
  739. CShootingAnimation::nextFrame();
  740. if ( explosionEmitted)
  741. return;
  742. if ( !projectileEmitted)
  743. return;
  744. if (owner->projectilesController->hasActiveProjectile(attackingStack))
  745. return;
  746. explosionEmitted = true;
  747. Point shotTarget = owner->stacksController->getStackPositionAtHex(dest, attackedStack) + Point(225, 225) - Point(126, 105);
  748. if(catapultDamage > 0)
  749. owner->stacksController->addNewAnim( new CPointEffectAnimation(owner, soundBase::WALLHIT, "SGEXPL.DEF", shotTarget));
  750. else
  751. owner->stacksController->addNewAnim( new CPointEffectAnimation(owner, soundBase::WALLMISS, "CSGRCK.DEF", shotTarget));
  752. }
  753. void CCatapultAnimation::createProjectile(const Point & from, const Point & dest) const
  754. {
  755. owner->projectilesController->createCatapultProjectile(attackingStack, from, dest);
  756. }
  757. CCastAnimation::CCastAnimation(CBattleInterface * owner_, const CStack * attacker, BattleHex dest_, const CStack * defender, const CSpell * spell)
  758. : CRangedAttackAnimation(owner_, attacker, dest_, defender),
  759. spell(spell)
  760. {
  761. assert(dest.isValid());// FIXME: when?
  762. if(!dest_.isValid() && defender)
  763. dest = defender->getPosition();
  764. }
  765. CCreatureAnim::EAnimType CCastAnimation::findValidGroup( const std::vector<CCreatureAnim::EAnimType> candidates ) const
  766. {
  767. for ( auto group : candidates)
  768. {
  769. if(myAnim->framesInGroup(group) > 0)
  770. return group;
  771. }
  772. assert(0);
  773. return CCreatureAnim::HOLDING;
  774. }
  775. CCreatureAnim::EAnimType CCastAnimation::getUpwardsGroup() const
  776. {
  777. return findValidGroup({
  778. CCreatureAnim::VCMI_CAST_UP,
  779. CCreatureAnim::CAST_UP,
  780. CCreatureAnim::SHOOT_UP,
  781. CCreatureAnim::ATTACK_UP
  782. });
  783. }
  784. CCreatureAnim::EAnimType CCastAnimation::getForwardGroup() const
  785. {
  786. return findValidGroup({
  787. CCreatureAnim::VCMI_CAST_FRONT,
  788. CCreatureAnim::CAST_FRONT,
  789. CCreatureAnim::SHOOT_FRONT,
  790. CCreatureAnim::ATTACK_FRONT
  791. });
  792. }
  793. CCreatureAnim::EAnimType CCastAnimation::getDownwardsGroup() const
  794. {
  795. return findValidGroup({
  796. CCreatureAnim::VCMI_CAST_DOWN,
  797. CCreatureAnim::CAST_DOWN,
  798. CCreatureAnim::SHOOT_DOWN,
  799. CCreatureAnim::ATTACK_DOWN
  800. });
  801. }
  802. void CCastAnimation::createProjectile(const Point & from, const Point & dest) const
  803. {
  804. if (!spell->animationInfo.projectile.empty())
  805. owner->projectilesController->createSpellProjectile(attackingStack, attackedStack, from, dest, spell);
  806. }
  807. CPointEffectAnimation::CPointEffectAnimation(CBattleInterface * _owner, soundBase::soundID sound, std::string animationName, int effects):
  808. CBattleAnimation(_owner),
  809. animation(std::make_shared<CAnimation>(animationName)),
  810. sound(sound),
  811. effectFlags(effects),
  812. soundPlayed(false),
  813. soundFinished(false),
  814. effectFinished(false)
  815. {
  816. }
  817. CPointEffectAnimation::CPointEffectAnimation(CBattleInterface * _owner, soundBase::soundID sound, std::string animationName, std::vector<BattleHex> pos, int effects):
  818. CPointEffectAnimation(_owner, sound, animationName, effects)
  819. {
  820. battlehexes = pos;
  821. }
  822. CPointEffectAnimation::CPointEffectAnimation(CBattleInterface * _owner, soundBase::soundID sound, std::string animationName, BattleHex pos, int effects):
  823. CPointEffectAnimation(_owner, sound, animationName, effects)
  824. {
  825. assert(pos.isValid());
  826. battlehexes.push_back(pos);
  827. }
  828. CPointEffectAnimation::CPointEffectAnimation(CBattleInterface * _owner, soundBase::soundID sound, std::string animationName, std::vector<Point> pos, int effects):
  829. CPointEffectAnimation(_owner, sound, animationName, effects)
  830. {
  831. positions = pos;
  832. }
  833. CPointEffectAnimation::CPointEffectAnimation(CBattleInterface * _owner, soundBase::soundID sound, std::string animationName, Point pos, int effects):
  834. CPointEffectAnimation(_owner, sound, animationName, effects)
  835. {
  836. positions.push_back(pos);
  837. }
  838. bool CPointEffectAnimation::init()
  839. {
  840. if(!CBattleAnimation::checkInitialConditions())
  841. return false;
  842. animation->preload();
  843. auto first = animation->getImage(0, 0, true);
  844. if(!first)
  845. {
  846. delete this;
  847. return false;
  848. }
  849. if (positions.empty() && battlehexes.empty())
  850. {
  851. //armageddon, create screen fill
  852. for(int i=0; i * first->width() < owner->pos.w ; ++i)
  853. for(int j=0; j * first->height() < owner->pos.h ; ++j)
  854. positions.push_back(Point(i * first->width(), j * first->height()));
  855. }
  856. BattleEffect be;
  857. be.effectID = ID;
  858. be.animation = animation;
  859. be.currentFrame = 0;
  860. for ( auto const position : positions)
  861. {
  862. be.x = position.x;
  863. be.y = position.y;
  864. be.position = BattleHex::INVALID;
  865. owner->effectsController->battleEffects.push_back(be);
  866. }
  867. for ( auto const tile : battlehexes)
  868. {
  869. const CStack * destStack = owner->getCurrentPlayerInterface()->cb->battleGetStackByPos(tile, false);
  870. assert(tile.isValid());
  871. if(!tile.isValid())
  872. continue;
  873. Rect tilePos = owner->fieldController->hexPosition(tile);
  874. be.position = tile;
  875. be.x = tilePos.x + tilePos.w/2 - first->width()/2;
  876. if(destStack && destStack->doubleWide()) // Correction for 2-hex creatures.
  877. be.x += (destStack->side == BattleSide::ATTACKER ? -1 : 1)*tilePos.w/2;
  878. if (alignToBottom())
  879. be.y = tilePos.y + tilePos.h - first->height();
  880. else
  881. be.y = tilePos.y - first->height()/2;
  882. owner->effectsController->battleEffects.push_back(be);
  883. }
  884. return true;
  885. }
  886. void CPointEffectAnimation::nextFrame()
  887. {
  888. playSound();
  889. playEffect();
  890. if (soundFinished && effectFinished)
  891. delete this;
  892. }
  893. bool CPointEffectAnimation::alignToBottom() const
  894. {
  895. return effectFlags & ALIGN_TO_BOTTOM;
  896. }
  897. bool CPointEffectAnimation::waitForSound() const
  898. {
  899. return effectFlags & WAIT_FOR_SOUND;
  900. }
  901. void CPointEffectAnimation::onEffectFinished()
  902. {
  903. effectFinished = true;
  904. clearEffect();
  905. }
  906. void CPointEffectAnimation::onSoundFinished()
  907. {
  908. soundFinished = true;
  909. }
  910. void CPointEffectAnimation::playSound()
  911. {
  912. if (soundPlayed)
  913. return;
  914. soundPlayed = true;
  915. if (sound == soundBase::invalid)
  916. {
  917. onSoundFinished();
  918. return;
  919. }
  920. int channel = CCS->soundh->playSound(sound);
  921. if (!waitForSound() || channel == -1)
  922. onSoundFinished();
  923. else
  924. CCS->soundh->setCallback(channel, [&](){ onSoundFinished(); });
  925. }
  926. void CPointEffectAnimation::playEffect()
  927. {
  928. for(auto & elem : owner->effectsController->battleEffects)
  929. {
  930. if(elem.effectID == ID)
  931. {
  932. elem.currentFrame += AnimationControls::getSpellEffectSpeed() * GH.mainFPSmng->getElapsedMilliseconds() / 1000;
  933. if(elem.currentFrame >= elem.animation->size())
  934. {
  935. onEffectFinished();
  936. break;
  937. }
  938. }
  939. }
  940. }
  941. void CPointEffectAnimation::clearEffect()
  942. {
  943. auto & effects = owner->effectsController->battleEffects;
  944. for ( auto it = effects.begin(); it != effects.end(); )
  945. {
  946. if (it->effectID == ID)
  947. it = effects.erase(it);
  948. else
  949. it++;
  950. }
  951. }
  952. CPointEffectAnimation::~CPointEffectAnimation()
  953. {
  954. assert(effectFinished);
  955. assert(soundFinished);
  956. }
  957. CWaitingAnimation::CWaitingAnimation(CBattleInterface * owner_):
  958. CBattleAnimation(owner_)
  959. {}
  960. void CWaitingAnimation::nextFrame()
  961. {
  962. // initialization conditions fulfilled, delay is over
  963. delete this;
  964. }
  965. CWaitingProjectileAnimation::CWaitingProjectileAnimation(CBattleInterface * owner_, const CStack * shooter):
  966. CWaitingAnimation(owner_),
  967. shooter(shooter)
  968. {}
  969. bool CWaitingProjectileAnimation::init()
  970. {
  971. for(auto & elem : pendingAnimations())
  972. {
  973. auto * attackAnim = dynamic_cast<CRangedAttackAnimation *>(elem);
  974. if( attackAnim && shooter && attackAnim->stack->ID == shooter->ID && !attackAnim->isInitialized() )
  975. {
  976. // there is ongoing ranged attack that involves our stack, but projectile was not created yet
  977. return false;
  978. }
  979. }
  980. if(owner->projectilesController->hasActiveProjectile(shooter))
  981. return false;
  982. return true;
  983. }