CBattleAnimations.cpp 29 KB

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