CBattleAnimations.cpp 29 KB

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