CBattleAnimations.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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/CAnimation.h"
  22. #include "../gui/CCursorHandler.h"
  23. #include "../gui/CGuiHandler.h"
  24. #include "../gui/SDL_Extensions.h"
  25. #include "../../CCallback.h"
  26. #include "../../lib/CStack.h"
  27. #include "../../lib/CTownHandler.h"
  28. #include "../../lib/mapObjects/CGTownInstance.h"
  29. #include "../../lib/spells/CSpellHandler.h"
  30. CBattleAnimation::CBattleAnimation(CBattleInterface * _owner)
  31. : owner(_owner), ID(_owner->animIDhelper++)
  32. {
  33. logAnim->trace("Animation #%d created", ID);
  34. }
  35. CBattleAnimation::~CBattleAnimation()
  36. {
  37. logAnim->trace("Animation #%d deleted", ID);
  38. }
  39. void CBattleAnimation::endAnim()
  40. {
  41. logAnim->trace("Animation #%d ended, type is %s", ID, typeid(this).name());
  42. for(auto & elem : owner->pendingAnims)
  43. {
  44. if(elem.first == this)
  45. {
  46. elem.first = nullptr;
  47. }
  48. }
  49. }
  50. bool CBattleAnimation::isEarliest(bool perStackConcurrency)
  51. {
  52. int lowestMoveID = owner->animIDhelper + 5;
  53. CBattleStackAnimation * thAnim = dynamic_cast<CBattleStackAnimation *>(this);
  54. CSpellEffectAnimation * thSen = dynamic_cast<CSpellEffectAnimation *>(this);
  55. for(auto & elem : owner->pendingAnims)
  56. {
  57. CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(elem.first);
  58. CSpellEffectAnimation * sen = dynamic_cast<CSpellEffectAnimation *>(elem.first);
  59. if(perStackConcurrency && stAnim && thAnim && stAnim->stack->ID != thAnim->stack->ID)
  60. continue;
  61. if(perStackConcurrency && sen && thSen && sen != thSen)
  62. continue;
  63. CReverseAnimation * revAnim = dynamic_cast<CReverseAnimation *>(stAnim);
  64. if(revAnim && thAnim && stAnim && stAnim->stack->ID == thAnim->stack->ID && revAnim->priority)
  65. return false;
  66. if(elem.first)
  67. vstd::amin(lowestMoveID, elem.first->ID);
  68. }
  69. return (ID == lowestMoveID) || (lowestMoveID == (owner->animIDhelper + 5));
  70. }
  71. CBattleStackAnimation::CBattleStackAnimation(CBattleInterface * owner, const CStack * stack)
  72. : CBattleAnimation(owner),
  73. myAnim(owner->creAnims[stack->ID]),
  74. stack(stack)
  75. {
  76. assert(myAnim);
  77. }
  78. void CAttackAnimation::nextFrame()
  79. {
  80. if(myAnim->getType() != group)
  81. {
  82. myAnim->setType(group);
  83. myAnim->onAnimationReset += std::bind(&CAttackAnimation::endAnim, this);
  84. }
  85. if(!soundPlayed)
  86. {
  87. if(shooting)
  88. CCS->soundh->playSound(battle_sound(attackingStack->getCreature(), shoot));
  89. else
  90. CCS->soundh->playSound(battle_sound(attackingStack->getCreature(), attack));
  91. soundPlayed = true;
  92. }
  93. CBattleAnimation::nextFrame();
  94. }
  95. void CAttackAnimation::endAnim()
  96. {
  97. myAnim->setType(CCreatureAnim::HOLDING);
  98. CBattleStackAnimation::endAnim();
  99. }
  100. bool CAttackAnimation::checkInitialConditions()
  101. {
  102. for(auto & elem : owner->pendingAnims)
  103. {
  104. CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(elem.first);
  105. CReverseAnimation * revAnim = dynamic_cast<CReverseAnimation *>(stAnim);
  106. if(revAnim && attackedStack) // enemy must be fully reversed
  107. {
  108. if (revAnim->stack->ID == attackedStack->ID)
  109. return false;
  110. }
  111. }
  112. return isEarliest(false);
  113. }
  114. CAttackAnimation::CAttackAnimation(CBattleInterface *_owner, const CStack *attacker, BattleHex _dest, const CStack *defender)
  115. : CBattleStackAnimation(_owner, attacker),
  116. shooting(false), group(CCreatureAnim::SHOOT_FRONT),
  117. soundPlayed(false),
  118. dest(_dest), attackedStack(defender), attackingStack(attacker)
  119. {
  120. assert(attackingStack && "attackingStack is nullptr in CBattleAttack::CBattleAttack !\n");
  121. bool isCatapultAttack = attackingStack->hasBonusOfType(Bonus::CATAPULT)
  122. && owner->getCurrentPlayerInterface()->cb->battleHexToWallPart(_dest) >= 0;
  123. assert(attackedStack || isCatapultAttack);
  124. UNUSED(isCatapultAttack);
  125. attackingStackPosBeforeReturn = attackingStack->position;
  126. }
  127. CDefenceAnimation::CDefenceAnimation(StackAttackedInfo _attackedInfo, CBattleInterface * _owner)
  128. : CBattleStackAnimation(_owner, _attackedInfo.defender),
  129. attacker(_attackedInfo.attacker), rangedAttack(_attackedInfo.indirectAttack),
  130. killed(_attackedInfo.killed), timeToWait(0)
  131. {
  132. logAnim->debug("Created defence anim for %s", _attackedInfo.defender->getName());
  133. }
  134. bool CDefenceAnimation::init()
  135. {
  136. if(attacker == nullptr && owner->battleEffects.size() > 0)
  137. return false;
  138. ui32 lowestMoveID = owner->animIDhelper + 5;
  139. for(auto & elem : owner->pendingAnims)
  140. {
  141. CDefenceAnimation * defAnim = dynamic_cast<CDefenceAnimation *>(elem.first);
  142. if(defAnim && defAnim->stack->ID != stack->ID)
  143. continue;
  144. CAttackAnimation * attAnim = dynamic_cast<CAttackAnimation *>(elem.first);
  145. if(attAnim && attAnim->stack->ID != stack->ID)
  146. continue;
  147. CSpellEffectAnimation * sen = dynamic_cast<CSpellEffectAnimation *>(elem.first);
  148. if (sen)
  149. continue;
  150. CReverseAnimation * animAsRev = dynamic_cast<CReverseAnimation *>(elem.first);
  151. if(animAsRev)
  152. return false;
  153. if(elem.first)
  154. vstd::amin(lowestMoveID, elem.first->ID);
  155. }
  156. if(ID > lowestMoveID)
  157. return false;
  158. //reverse unit if necessary
  159. if (attacker && owner->getCurrentPlayerInterface()->cb->isToReverse(stack->position, attacker->position, owner->creDir[stack->ID], attacker->doubleWide(), owner->creDir[attacker->ID]))
  160. {
  161. owner->addNewAnim(new CReverseAnimation(owner, stack, stack->position, true));
  162. return false;
  163. }
  164. //unit reversed
  165. if(rangedAttack) //delay hit animation
  166. {
  167. for(std::list<ProjectileInfo>::const_iterator it = owner->projectiles.begin(); it != owner->projectiles.end(); ++it)
  168. {
  169. if(it->creID == attacker->getCreature()->idNumber)
  170. {
  171. return false;
  172. }
  173. }
  174. }
  175. // synchronize animation with attacker, unless defending or attacked by shooter:
  176. // wait for 1/2 of attack animation
  177. if (!rangedAttack && getMyAnimType() != CCreatureAnim::DEFENCE)
  178. {
  179. float frameLength = AnimationControls::getCreatureAnimationSpeed(
  180. stack->getCreature(), owner->creAnims[stack->ID], getMyAnimType());
  181. timeToWait = myAnim->framesInGroup(getMyAnimType()) * frameLength / 2;
  182. myAnim->setType(CCreatureAnim::HOLDING);
  183. }
  184. else
  185. {
  186. timeToWait = 0;
  187. startAnimation();
  188. }
  189. return true; //initialized successfuly
  190. }
  191. std::string CDefenceAnimation::getMySound()
  192. {
  193. if(killed)
  194. return battle_sound(stack->getCreature(), killed);
  195. if (vstd::contains(stack->state, EBattleStackState::DEFENDING_ANIM))
  196. return battle_sound(stack->getCreature(), defend);
  197. return battle_sound(stack->getCreature(), wince);
  198. }
  199. CCreatureAnim::EAnimType CDefenceAnimation::getMyAnimType()
  200. {
  201. if(killed)
  202. return CCreatureAnim::DEATH;
  203. if (vstd::contains(stack->state, EBattleStackState::DEFENDING_ANIM))
  204. return CCreatureAnim::DEFENCE;
  205. return CCreatureAnim::HITTED;
  206. }
  207. void CDefenceAnimation::startAnimation()
  208. {
  209. CCS->soundh->playSound(getMySound());
  210. myAnim->setType(getMyAnimType());
  211. myAnim->onAnimationReset += std::bind(&CDefenceAnimation::endAnim, this);
  212. }
  213. void CDefenceAnimation::nextFrame()
  214. {
  215. if (timeToWait > 0)
  216. {
  217. timeToWait -= float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000;
  218. if (timeToWait <= 0)
  219. startAnimation();
  220. }
  221. CBattleAnimation::nextFrame();
  222. }
  223. void CDefenceAnimation::endAnim()
  224. {
  225. if (killed)
  226. myAnim->setType(CCreatureAnim::DEAD);
  227. else
  228. myAnim->setType(CCreatureAnim::HOLDING);
  229. CBattleAnimation::endAnim();
  230. delete this;
  231. }
  232. CDummyAnimation::CDummyAnimation(CBattleInterface * _owner, int howManyFrames)
  233. : CBattleAnimation(_owner), counter(0), howMany(howManyFrames)
  234. {
  235. logAnim->debug("Created dummy animation for %d frames", howManyFrames);
  236. }
  237. bool CDummyAnimation::init()
  238. {
  239. return true;
  240. }
  241. void CDummyAnimation::nextFrame()
  242. {
  243. counter++;
  244. if(counter > howMany)
  245. endAnim();
  246. }
  247. void CDummyAnimation::endAnim()
  248. {
  249. CBattleAnimation::endAnim();
  250. delete this;
  251. }
  252. bool CMeleeAttackAnimation::init()
  253. {
  254. if( !CAttackAnimation::checkInitialConditions() )
  255. return false;
  256. if(!attackingStack || myAnim->isDead())
  257. {
  258. endAnim();
  259. return false;
  260. }
  261. bool toReverse = owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStackPosBeforeReturn, attackedStack->position, owner->creDir[stack->ID], attackedStack->doubleWide(), owner->creDir[attackedStack->ID]);
  262. if (toReverse)
  263. {
  264. owner->addNewAnim(new CReverseAnimation(owner, stack, attackingStackPosBeforeReturn, true));
  265. return false;
  266. }
  267. // opponent must face attacker ( = different directions) before he can be attacked
  268. if (attackingStack && attackedStack &&
  269. owner->creDir[attackingStack->ID] == owner->creDir[attackedStack->ID])
  270. return false;
  271. //reversed
  272. shooting = false;
  273. static const CCreatureAnim::EAnimType mutPosToGroup[] = {CCreatureAnim::ATTACK_UP, CCreatureAnim::ATTACK_UP,
  274. CCreatureAnim::ATTACK_FRONT, CCreatureAnim::ATTACK_DOWN, CCreatureAnim::ATTACK_DOWN, CCreatureAnim::ATTACK_FRONT};
  275. int revShiftattacker = (attackingStack->side == BattleSide::ATTACKER ? -1 : 1);
  276. int mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, dest);
  277. if(mutPos == -1 && attackingStack->doubleWide())
  278. {
  279. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->position);
  280. }
  281. if (mutPos == -1 && attackedStack->doubleWide())
  282. {
  283. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, attackedStack->occupiedHex());
  284. }
  285. if (mutPos == -1 && attackedStack->doubleWide() && attackingStack->doubleWide())
  286. {
  287. mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->occupiedHex());
  288. }
  289. switch(mutPos) //attack direction
  290. {
  291. case 0: case 1: case 2: case 3: case 4: case 5:
  292. group = mutPosToGroup[mutPos];
  293. break;
  294. default:
  295. logGlobal->error("Critical Error! Wrong dest in stackAttacking! dest: %d; attacking stack pos: %d; mutual pos: %d", dest.hex, attackingStackPosBeforeReturn, 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->debug("Created melee attack anim for %s", 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),
  427. destTiles(_destTiles),
  428. curentMoveIndex(0),
  429. oldPos(stack->position),
  430. begX(0), begY(0),
  431. distanceX(0), distanceY(0),
  432. timeToMove(0.0),
  433. progress(0.0),
  434. nextHex(destTiles.front())
  435. {
  436. logAnim->debug("Created movement anim for %s", stack->getName());
  437. }
  438. CMovementEndAnimation::CMovementEndAnimation(CBattleInterface * _owner, const CStack * _stack, BattleHex destTile)
  439. : CBattleStackAnimation(_owner, _stack), destinationTile(destTile)
  440. {
  441. logAnim->debug("Created movement end anim for %s", stack->getName());
  442. }
  443. bool CMovementEndAnimation::init()
  444. {
  445. if( !isEarliest(true) )
  446. return false;
  447. if(!stack || myAnim->framesInGroup(CCreatureAnim::MOVE_END) == 0 ||
  448. myAnim->isDead())
  449. {
  450. endAnim();
  451. return false;
  452. }
  453. CCS->soundh->playSound(battle_sound(stack->getCreature(), endMoving));
  454. myAnim->setType(CCreatureAnim::MOVE_END);
  455. myAnim->onAnimationReset += std::bind(&CMovementEndAnimation::endAnim, this);
  456. return true;
  457. }
  458. void CMovementEndAnimation::endAnim()
  459. {
  460. CBattleAnimation::endAnim();
  461. if(myAnim->getType() != CCreatureAnim::DEAD)
  462. myAnim->setType(CCreatureAnim::HOLDING); //resetting to default
  463. CCS->curh->show();
  464. delete this;
  465. }
  466. CMovementStartAnimation::CMovementStartAnimation(CBattleInterface * _owner, const CStack * _stack)
  467. : CBattleStackAnimation(_owner, _stack)
  468. {
  469. logAnim->debug("Created movement start anim for %s", stack->getName());
  470. }
  471. bool CMovementStartAnimation::init()
  472. {
  473. if( !isEarliest(false) )
  474. return false;
  475. if(!stack || myAnim->isDead())
  476. {
  477. CMovementStartAnimation::endAnim();
  478. return false;
  479. }
  480. CCS->soundh->playSound(battle_sound(stack->getCreature(), startMoving));
  481. myAnim->setType(CCreatureAnim::MOVE_START);
  482. myAnim->onAnimationReset += std::bind(&CMovementStartAnimation::endAnim, this);
  483. return true;
  484. }
  485. void CMovementStartAnimation::endAnim()
  486. {
  487. CBattleAnimation::endAnim();
  488. delete this;
  489. }
  490. CReverseAnimation::CReverseAnimation(CBattleInterface * _owner, const CStack * stack, BattleHex dest, bool _priority)
  491. : CBattleStackAnimation(_owner, stack), hex(dest), priority(_priority)
  492. {
  493. logAnim->debug("Created reverse anim for %s", stack->getName());
  494. }
  495. bool CReverseAnimation::init()
  496. {
  497. if(myAnim == nullptr || myAnim->isDead())
  498. {
  499. endAnim();
  500. return false; //there is no such creature
  501. }
  502. if(!priority && !isEarliest(false))
  503. return false;
  504. if(myAnim->framesInGroup(CCreatureAnim::TURN_L))
  505. {
  506. myAnim->setType(CCreatureAnim::TURN_L);
  507. myAnim->onAnimationReset += std::bind(&CReverseAnimation::setupSecondPart, this);
  508. }
  509. else
  510. {
  511. setupSecondPart();
  512. }
  513. return true;
  514. }
  515. void CReverseAnimation::endAnim()
  516. {
  517. CBattleAnimation::endAnim();
  518. if( stack->alive() )//don't do that if stack is dead
  519. myAnim->setType(CCreatureAnim::HOLDING);
  520. delete this;
  521. }
  522. void CReverseAnimation::rotateStack(CBattleInterface * owner, const CStack * stack, BattleHex hex)
  523. {
  524. owner->creDir[stack->ID] = !owner->creDir[stack->ID];
  525. owner->creAnims[stack->ID]->pos = CClickableHex::getXYUnitAnim(hex, stack, owner);
  526. }
  527. void CReverseAnimation::setupSecondPart()
  528. {
  529. if(!stack)
  530. {
  531. endAnim();
  532. return;
  533. }
  534. rotateStack(owner, stack, hex);
  535. if(myAnim->framesInGroup(CCreatureAnim::TURN_R))
  536. {
  537. myAnim->setType(CCreatureAnim::TURN_R);
  538. myAnim->onAnimationReset += std::bind(&CReverseAnimation::endAnim, this);
  539. }
  540. else
  541. endAnim();
  542. }
  543. CShootingAnimation::CShootingAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, bool _catapult, int _catapultDmg)
  544. : CAttackAnimation(_owner, attacker, _dest, _attacked), catapultDamage(_catapultDmg)
  545. {
  546. logAnim->debug("Created shooting anim for %s", stack->getName());
  547. }
  548. bool CShootingAnimation::init()
  549. {
  550. if( !CAttackAnimation::checkInitialConditions() )
  551. return false;
  552. const CStack * shooter = attackingStack;
  553. if(!shooter || myAnim->isDead())
  554. {
  555. endAnim();
  556. return false;
  557. }
  558. //reverse unit if necessary
  559. if (attackingStack && attackedStack && owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStack->position, attackedStack->position, owner->creDir[attackingStack->ID], attackingStack->doubleWide(), owner->creDir[attackedStack->ID]))
  560. {
  561. owner->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->position, true));
  562. return false;
  563. }
  564. // opponent must face attacker ( = different directions) before he can be attacked
  565. if (attackingStack && attackedStack &&
  566. owner->creDir[attackingStack->ID] == owner->creDir[attackedStack->ID])
  567. return false;
  568. // Create the projectile animation
  569. //maximal angle in radians between straight horizontal line and shooting line for which shot is considered to be straight (absoulte value)
  570. static const double straightAngle = 0.2;
  571. // Get further info about the shooter e.g. relative pos of projectile to unit.
  572. // If the creature id is 149 then it's a arrow tower which has no additional info so get the
  573. // actual arrow tower shooter instead.
  574. const CCreature *shooterInfo = shooter->getCreature();
  575. if (shooterInfo->idNumber == CreatureID::ARROW_TOWERS)
  576. {
  577. int creID = owner->siegeH->town->town->clientInfo.siegeShooter;
  578. shooterInfo = CGI->creh->creatures[creID];
  579. }
  580. ProjectileInfo spi;
  581. spi.shotDone = false;
  582. spi.creID = shooter->getCreature()->idNumber;
  583. spi.stackID = shooter->ID;
  584. // reverse if creature is facing right OR this is non-existing stack that is not tower (war machines)
  585. spi.reverse = attackingStack ? !owner->creDir[attackingStack->ID] : shooter->getCreature()->idNumber != CreatureID::ARROW_TOWERS ;
  586. spi.step = 0;
  587. spi.frameNum = 0;
  588. Point fromPos;
  589. Point destPos;
  590. // NOTE: two lines below return different positions (very notable with 2-hex creatures). Obtaining via creanims seems to be more precise
  591. fromPos = owner->creAnims[spi.stackID]->pos.topLeft();
  592. //xycoord = CClickableHex::getXYUnitAnim(shooter->position, true, shooter, owner);
  593. destPos = CClickableHex::getXYUnitAnim(dest, attackedStack, owner);
  594. // to properly translate coordinates when shooter is rotated
  595. int multiplier = spi.reverse ? -1 : 1;
  596. double projectileAngle = atan2(fabs((double)destPos.y - fromPos.y), fabs((double)destPos.x - fromPos.x));
  597. if(shooter->position < dest)
  598. projectileAngle = -projectileAngle;
  599. // Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
  600. if (projectileAngle > straightAngle)
  601. {
  602. //upper shot
  603. spi.x = fromPos.x + 222 + ( -25 + shooterInfo->animation.upperRightMissleOffsetX ) * multiplier;
  604. spi.y = fromPos.y + 265 + shooterInfo->animation.upperRightMissleOffsetY;
  605. }
  606. else if (projectileAngle < -straightAngle)
  607. {
  608. //lower shot
  609. spi.x = fromPos.x + 222 + ( -25 + shooterInfo->animation.lowerRightMissleOffsetX ) * multiplier;
  610. spi.y = fromPos.y + 265 + shooterInfo->animation.lowerRightMissleOffsetY;
  611. }
  612. else
  613. {
  614. //straight shot
  615. spi.x = fromPos.x + 222 + ( -25 + shooterInfo->animation.rightMissleOffsetX ) * multiplier;
  616. spi.y = fromPos.y + 265 + shooterInfo->animation.rightMissleOffsetY;
  617. }
  618. destPos += Point(225, 225);
  619. // recalculate angle taking in account offsets
  620. //projectileAngle = atan2(fabs(destPos.y - spi.y), fabs(destPos.x - spi.x));
  621. //if(shooter->position < dest)
  622. // projectileAngle = -projectileAngle;
  623. if (attackedStack)
  624. {
  625. double animSpeed = AnimationControls::getProjectileSpeed(); // flight speed of projectile
  626. 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);
  627. if(spi.lastStep == 0)
  628. spi.lastStep = 1;
  629. spi.dx = (destPos.x - spi.x) / spi.lastStep;
  630. spi.dy = (destPos.y - spi.y) / spi.lastStep;
  631. }
  632. else
  633. {
  634. // Catapult attack
  635. spi.catapultInfo.reset(new CatapultProjectileInfo(Point(spi.x, spi.y), destPos));
  636. double animSpeed = AnimationControls::getProjectileSpeed() / 10;
  637. spi.lastStep = std::abs((destPos.x - spi.x) / animSpeed);
  638. spi.dx = animSpeed;
  639. spi.dy = 0;
  640. SDL_Surface * img = owner->idToProjectile[spi.creID]->ourImages[0].bitmap;
  641. // Add explosion anim
  642. Point animPos(destPos.x - 126 + img->w / 2,
  643. destPos.y - 105 + img->h / 2);
  644. owner->addNewAnim( new CSpellEffectAnimation(owner, catapultDamage ? "SGEXPL.DEF" : "CSGRCK.DEF", animPos.x, animPos.y));
  645. }
  646. auto & angles = shooterInfo->animation.missleFrameAngles;
  647. double pi = boost::math::constants::pi<double>();
  648. 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
  649. owner->initStackProjectile(shooter);
  650. // only frames below maxFrame are usable: anything higher is either no present or we don't know when it should be used
  651. size_t maxFrame = std::min<size_t>(angles.size(), owner->idToProjectile.at(spi.creID)->ourImages.size());
  652. assert(maxFrame > 0);
  653. // values in angles array indicate position from which this frame was rendered, in degrees.
  654. // find frame that has closest angle to one that we need for this shot
  655. size_t bestID = 0;
  656. double bestDiff = fabs( angles[0] / 180 * pi - projectileAngle );
  657. for (size_t i=1; i<maxFrame; i++)
  658. {
  659. double currentDiff = fabs( angles[i] / 180 * pi - projectileAngle );
  660. if (currentDiff < bestDiff)
  661. {
  662. bestID = i;
  663. bestDiff = currentDiff;
  664. }
  665. }
  666. spi.frameNum = bestID;
  667. // Set projectile animation start delay which is specified in frames
  668. spi.animStartDelay = shooterInfo->animation.attackClimaxFrame;
  669. owner->projectiles.push_back(spi);
  670. //attack animation
  671. shooting = true;
  672. if(projectileAngle > straightAngle) //upper shot
  673. group = CCreatureAnim::SHOOT_UP;
  674. else if(projectileAngle < -straightAngle) //lower shot
  675. group = CCreatureAnim::SHOOT_DOWN;
  676. else //straight shot
  677. group = CCreatureAnim::SHOOT_FRONT;
  678. return true;
  679. }
  680. void CShootingAnimation::nextFrame()
  681. {
  682. for(auto & it : owner->pendingAnims)
  683. {
  684. CMovementStartAnimation * anim = dynamic_cast<CMovementStartAnimation *>(it.first);
  685. CReverseAnimation * anim2 = dynamic_cast<CReverseAnimation *>(it.first);
  686. if( (anim && anim->stack->ID == stack->ID) || (anim2 && anim2->stack->ID == stack->ID && anim2->priority ) )
  687. return;
  688. }
  689. CAttackAnimation::nextFrame();
  690. }
  691. void CShootingAnimation::endAnim()
  692. {
  693. // play wall hit/miss sound for catapult attack
  694. if(!attackedStack)
  695. {
  696. if(catapultDamage > 0)
  697. {
  698. CCS->soundh->playSound("WALLHIT");
  699. }
  700. else
  701. {
  702. CCS->soundh->playSound("WALLMISS");
  703. }
  704. }
  705. CAttackAnimation::endAnim();
  706. delete this;
  707. }
  708. CSpellEffectAnimation::CSpellEffectAnimation(CBattleInterface * _owner, ui32 _effect, BattleHex _destTile, int _dx, int _dy, bool _Vflip, bool _alignToBottom)
  709. :CBattleAnimation(_owner), effect(_effect), destTile(_destTile), customAnim(""), x(-1), y(-1), dx(_dx), dy(_dy), Vflip(_Vflip), alignToBottom(_alignToBottom)
  710. {
  711. logAnim->debug("Created spell anim for effect #%d", effect);
  712. }
  713. CSpellEffectAnimation::CSpellEffectAnimation(CBattleInterface * _owner, std::string _customAnim, int _x, int _y, int _dx, int _dy, bool _Vflip, bool _alignToBottom)
  714. :CBattleAnimation(_owner), effect(-1), destTile(BattleHex::INVALID), customAnim(_customAnim), x(_x), y(_y), dx(_dx), dy(_dy), Vflip(_Vflip), alignToBottom(_alignToBottom)
  715. {
  716. logAnim->debug("Created spell anim for %s", customAnim);
  717. }
  718. CSpellEffectAnimation::CSpellEffectAnimation(CBattleInterface * _owner, std::string _customAnim, BattleHex _destTile, bool _Vflip, bool _alignToBottom)
  719. :CBattleAnimation(_owner), effect(-1), destTile(_destTile), customAnim(_customAnim), x(-1), y(-1), dx(0), dy(0), Vflip(_Vflip), alignToBottom(_alignToBottom)
  720. {
  721. logAnim->debug("Created spell anim for %s", customAnim);
  722. }
  723. bool CSpellEffectAnimation::init()
  724. {
  725. if(!isEarliest(true))
  726. return false;
  727. if(customAnim.empty() && effect != ui32(-1) && !graphics->battleACToDef[effect].empty())
  728. {
  729. customAnim = graphics->battleACToDef[effect][0];
  730. }
  731. if(customAnim.empty())
  732. {
  733. endAnim();
  734. return false;
  735. }
  736. const bool areaEffect = (!destTile.isValid() && x == -1 && y == -1);
  737. std::shared_ptr<CAnimation> animation = std::make_shared<CAnimation>(customAnim);
  738. animation->preload();
  739. if(Vflip)
  740. animation->verticalFlip();
  741. IImage * first = animation->getImage(0, 0, true);
  742. if(!first)
  743. {
  744. endAnim();
  745. return false;
  746. }
  747. if(areaEffect) //f.e. armageddon
  748. {
  749. for(int i=0; i * first->width() < owner->pos.w ; ++i)
  750. {
  751. for(int j=0; j * first->height() < owner->pos.h ; ++j)
  752. {
  753. BattleEffect be;
  754. be.effectID = ID;
  755. be.animation = animation;
  756. be.currentFrame = 0;
  757. be.x = i * first->width() + owner->pos.x;
  758. be.y = j * first->height() + owner->pos.y;
  759. be.position = BattleHex::INVALID;
  760. owner->battleEffects.push_back(be);
  761. }
  762. }
  763. }
  764. else // Effects targeted at a specific creature/hex.
  765. {
  766. const CStack * destStack = owner->getCurrentPlayerInterface()->cb->battleGetStackByPos(destTile, false);
  767. Rect & tilePos = owner->bfield[destTile]->pos;
  768. BattleEffect be;
  769. be.effectID = ID;
  770. be.animation = animation;
  771. be.currentFrame = 0;
  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 - first->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 - first->height();
  787. else
  788. be.y = tilePos.y - first->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.animation->size())
  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. owner->battleEffects.erase(elem);
  839. }
  840. delete this;
  841. }