CBattleAnimations.cpp 33 KB

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