CBattleAnimations.cpp 33 KB

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