CBattleAnimations.cpp 33 KB

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