CBattleAnimations.cpp 29 KB

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