CBattleAnimations.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  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. if(!shooterInfo->animation.missleFrameAngles.size())
  628. logAnim->error("Mod error: Creature '%s' on the Archer's tower is not a shooter. Mod should be fixed. Trying to use archer's data instead..."
  629. , shooterInfo->nameSing);
  630. auto & angles = shooterInfo->animation.missleFrameAngles.size()
  631. ? shooterInfo->animation.missleFrameAngles
  632. : CGI->creh->creatures[CreatureID::ARCHER]->animation.missleFrameAngles;
  633. ProjectileInfo spi;
  634. spi.shotDone = false;
  635. spi.creID = shooter->getCreature()->idNumber;
  636. spi.stackID = shooter->ID;
  637. // reverse if creature is facing right OR this is non-existing stack that is not tower (war machines)
  638. spi.reverse = attackingStack ? !owner->creDir[attackingStack->ID] : shooter->getCreature()->idNumber != CreatureID::ARROW_TOWERS ;
  639. spi.step = 0;
  640. spi.frameNum = 0;
  641. Point fromPos;
  642. Point destPos;
  643. // NOTE: two lines below return different positions (very notable with 2-hex creatures). Obtaining via creanims seems to be more precise
  644. fromPos = owner->creAnims[spi.stackID]->pos.topLeft();
  645. //xycoord = CClickableHex::getXYUnitAnim(shooter->position, true, shooter, owner);
  646. destPos = CClickableHex::getXYUnitAnim(dest, attackedStack, owner);
  647. // to properly translate coordinates when shooter is rotated
  648. int multiplier = spi.reverse ? -1 : 1;
  649. double projectileAngle = atan2(fabs((double)destPos.y - fromPos.y), fabs((double)destPos.x - fromPos.x));
  650. if(shooter->getPosition() < dest)
  651. projectileAngle = -projectileAngle;
  652. // Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
  653. if (projectileAngle > straightAngle)
  654. {
  655. //upper shot
  656. spi.x = fromPos.x + 222 + ( -25 + shooterInfo->animation.upperRightMissleOffsetX ) * multiplier;
  657. spi.y = fromPos.y + 265 + shooterInfo->animation.upperRightMissleOffsetY;
  658. }
  659. else if (projectileAngle < -straightAngle)
  660. {
  661. //lower shot
  662. spi.x = fromPos.x + 222 + ( -25 + shooterInfo->animation.lowerRightMissleOffsetX ) * multiplier;
  663. spi.y = fromPos.y + 265 + shooterInfo->animation.lowerRightMissleOffsetY;
  664. }
  665. else
  666. {
  667. //straight shot
  668. spi.x = fromPos.x + 222 + ( -25 + shooterInfo->animation.rightMissleOffsetX ) * multiplier;
  669. spi.y = fromPos.y + 265 + shooterInfo->animation.rightMissleOffsetY;
  670. }
  671. destPos += Point(225, 225);
  672. // recalculate angle taking in account offsets
  673. //projectileAngle = atan2(fabs(destPos.y - spi.y), fabs(destPos.x - spi.x));
  674. //if(shooter->position < dest)
  675. // projectileAngle = -projectileAngle;
  676. if (attackedStack)
  677. {
  678. double animSpeed = AnimationControls::getProjectileSpeed(); // flight speed of projectile
  679. 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);
  680. if(spi.lastStep == 0)
  681. spi.lastStep = 1;
  682. spi.dx = (destPos.x - spi.x) / spi.lastStep;
  683. spi.dy = (destPos.y - spi.y) / spi.lastStep;
  684. }
  685. else
  686. {
  687. // Catapult attack
  688. spi.catapultInfo.reset(new CatapultProjectileInfo(Point((int)spi.x, (int)spi.y), destPos));
  689. double animSpeed = AnimationControls::getProjectileSpeed() / 10;
  690. spi.lastStep = static_cast<int>(std::abs((destPos.x - spi.x) / animSpeed));
  691. spi.dx = animSpeed;
  692. spi.dy = 0;
  693. auto img = owner->idToProjectile[spi.creID]->getImage(0);
  694. // Add explosion anim
  695. Point animPos(destPos.x - 126 + img->width() / 2,
  696. destPos.y - 105 + img->height() / 2);
  697. owner->addNewAnim( new CEffectAnimation(owner, catapultDamage ? "SGEXPL.DEF" : "CSGRCK.DEF", animPos.x, animPos.y));
  698. }
  699. double pi = boost::math::constants::pi<double>();
  700. 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
  701. owner->initStackProjectile(shooter);
  702. // only frames below maxFrame are usable: anything higher is either no present or we don't know when it should be used
  703. size_t maxFrame = std::min<size_t>(angles.size(), owner->idToProjectile.at(spi.creID)->size(0));
  704. assert(maxFrame > 0);
  705. // values in angles array indicate position from which this frame was rendered, in degrees.
  706. // find frame that has closest angle to one that we need for this shot
  707. size_t bestID = 0;
  708. double bestDiff = fabs( angles[0] / 180 * pi - projectileAngle );
  709. for (size_t i=1; i<maxFrame; i++)
  710. {
  711. double currentDiff = fabs( angles[i] / 180 * pi - projectileAngle );
  712. if (currentDiff < bestDiff)
  713. {
  714. bestID = i;
  715. bestDiff = currentDiff;
  716. }
  717. }
  718. spi.frameNum = static_cast<int>(bestID);
  719. // Set projectile animation start delay which is specified in frames
  720. spi.animStartDelay = shooterInfo->animation.attackClimaxFrame;
  721. owner->projectiles.push_back(spi);
  722. //attack animation
  723. shooting = true;
  724. if(projectileAngle > straightAngle)
  725. group = CCreatureAnim::SHOOT_UP;
  726. else if(projectileAngle < -straightAngle)
  727. group = CCreatureAnim::SHOOT_DOWN;
  728. else //straight shot
  729. group = CCreatureAnim::SHOOT_FRONT;
  730. return true;
  731. }
  732. void CShootingAnimation::nextFrame()
  733. {
  734. for(auto & it : owner->pendingAnims)
  735. {
  736. CMovementStartAnimation * anim = dynamic_cast<CMovementStartAnimation *>(it.first);
  737. CReverseAnimation * anim2 = dynamic_cast<CReverseAnimation *>(it.first);
  738. if( (anim && anim->stack->ID == stack->ID) || (anim2 && anim2->stack->ID == stack->ID && anim2->priority ) )
  739. return;
  740. }
  741. CAttackAnimation::nextFrame();
  742. }
  743. void CShootingAnimation::endAnim()
  744. {
  745. // play wall hit/miss sound for catapult attack
  746. if(!attackedStack)
  747. {
  748. if(catapultDamage > 0)
  749. {
  750. CCS->soundh->playSound("WALLHIT");
  751. }
  752. else
  753. {
  754. CCS->soundh->playSound("WALLMISS");
  755. }
  756. }
  757. CAttackAnimation::endAnim();
  758. delete this;
  759. }
  760. CCastAnimation::CCastAnimation(CBattleInterface * owner_, const CStack * attacker, BattleHex dest_, const CStack * defender)
  761. : CRangedAttackAnimation(owner_, attacker, dest_, defender)
  762. {
  763. if(!dest_.isValid() && defender)
  764. dest = defender->getPosition();
  765. }
  766. bool CCastAnimation::init()
  767. {
  768. if(!CAttackAnimation::checkInitialConditions())
  769. return false;
  770. if(!attackingStack || myAnim->isDead())
  771. {
  772. endAnim();
  773. return false;
  774. }
  775. //reverse unit if necessary
  776. if(attackedStack)
  777. {
  778. if(owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStack->getPosition(), attackedStack->getPosition(), owner->creDir[attackingStack->ID], attackingStack->doubleWide(), owner->creDir[attackedStack->ID]))
  779. {
  780. owner->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->getPosition(), true));
  781. return false;
  782. }
  783. }
  784. else
  785. {
  786. if(dest.isValid() && owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStack->getPosition(), dest, owner->creDir[attackingStack->ID], false, false))
  787. {
  788. owner->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->getPosition(), true));
  789. return false;
  790. }
  791. }
  792. //TODO: display spell projectile here
  793. static const double straightAngle = 0.2;
  794. Point fromPos;
  795. Point destPos;
  796. // NOTE: two lines below return different positions (very notable with 2-hex creatures). Obtaining via creanims seems to be more precise
  797. fromPos = owner->creAnims[attackingStack->ID]->pos.topLeft();
  798. //xycoord = CClickableHex::getXYUnitAnim(shooter->getPosition(), true, shooter, owner);
  799. destPos = CClickableHex::getXYUnitAnim(dest, attackedStack, owner);
  800. double projectileAngle = atan2(fabs((double)destPos.y - fromPos.y), fabs((double)destPos.x - fromPos.x));
  801. if(attackingStack->getPosition() < dest)
  802. projectileAngle = -projectileAngle;
  803. if(projectileAngle > straightAngle)
  804. group = CCreatureAnim::VCMI_CAST_UP;
  805. else if(projectileAngle < -straightAngle)
  806. group = CCreatureAnim::VCMI_CAST_DOWN;
  807. else
  808. group = CCreatureAnim::VCMI_CAST_FRONT;
  809. //fall back to H3 cast/2hex
  810. //even if creature have 2hex attack instead of cast it is ok since we fall back to attack anyway
  811. if(myAnim->framesInGroup(group) == 0)
  812. {
  813. if(projectileAngle > straightAngle)
  814. group = CCreatureAnim::CAST_UP;
  815. else if(projectileAngle < -straightAngle)
  816. group = CCreatureAnim::CAST_DOWN;
  817. else
  818. group = CCreatureAnim::CAST_FRONT;
  819. }
  820. //fall back to ranged attack
  821. if(myAnim->framesInGroup(group) == 0)
  822. {
  823. if(projectileAngle > straightAngle)
  824. group = CCreatureAnim::SHOOT_UP;
  825. else if(projectileAngle < -straightAngle)
  826. group = CCreatureAnim::SHOOT_DOWN;
  827. else
  828. group = CCreatureAnim::SHOOT_FRONT;
  829. }
  830. //fall back to normal attack
  831. if(myAnim->framesInGroup(group) == 0)
  832. {
  833. if(projectileAngle > straightAngle)
  834. group = CCreatureAnim::ATTACK_UP;
  835. else if(projectileAngle < -straightAngle)
  836. group = CCreatureAnim::ATTACK_DOWN;
  837. else
  838. group = CCreatureAnim::ATTACK_FRONT;
  839. }
  840. return true;
  841. }
  842. void CCastAnimation::nextFrame()
  843. {
  844. for(auto & it : owner->pendingAnims)
  845. {
  846. CReverseAnimation * anim = dynamic_cast<CReverseAnimation *>(it.first);
  847. if(anim && anim->stack->ID == stack->ID && anim->priority)
  848. return;
  849. }
  850. if(myAnim->getType() != group)
  851. {
  852. myAnim->setType(group);
  853. myAnim->onAnimationReset += std::bind(&CAttackAnimation::endAnim, this);
  854. }
  855. CBattleAnimation::nextFrame();
  856. }
  857. void CCastAnimation::endAnim()
  858. {
  859. CAttackAnimation::endAnim();
  860. delete this;
  861. }
  862. CEffectAnimation::CEffectAnimation(CBattleInterface * _owner, std::string _customAnim, int _x, int _y, int _dx, int _dy, bool _Vflip, bool _alignToBottom)
  863. : CBattleAnimation(_owner),
  864. destTile(BattleHex::INVALID),
  865. x(_x),
  866. y(_y),
  867. dx(_dx),
  868. dy(_dy),
  869. Vflip(_Vflip),
  870. alignToBottom(_alignToBottom)
  871. {
  872. logAnim->debug("Created effect animation %s", _customAnim);
  873. customAnim = std::make_shared<CAnimation>(_customAnim);
  874. }
  875. CEffectAnimation::CEffectAnimation(CBattleInterface * _owner, std::shared_ptr<CAnimation> _customAnim, int _x, int _y, int _dx, int _dy)
  876. : CBattleAnimation(_owner),
  877. destTile(BattleHex::INVALID),
  878. customAnim(_customAnim),
  879. x(_x),
  880. y(_y),
  881. dx(_dx),
  882. dy(_dy),
  883. Vflip(false),
  884. alignToBottom(false)
  885. {
  886. logAnim->debug("Created custom effect animation");
  887. }
  888. CEffectAnimation::CEffectAnimation(CBattleInterface * _owner, std::string _customAnim, BattleHex _destTile, bool _Vflip, bool _alignToBottom)
  889. : CBattleAnimation(_owner),
  890. destTile(_destTile),
  891. x(-1),
  892. y(-1),
  893. dx(0),
  894. dy(0),
  895. Vflip(_Vflip),
  896. alignToBottom(_alignToBottom)
  897. {
  898. logAnim->debug("Created effect animation %s", _customAnim);
  899. customAnim = std::make_shared<CAnimation>(_customAnim);
  900. }
  901. bool CEffectAnimation::init()
  902. {
  903. if(!isEarliest(true))
  904. return false;
  905. const bool areaEffect = (!destTile.isValid() && x == -1 && y == -1);
  906. std::shared_ptr<CAnimation> animation = customAnim;
  907. animation->preload();
  908. if(Vflip)
  909. animation->verticalFlip();
  910. auto first = animation->getImage(0, 0, true);
  911. if(!first)
  912. {
  913. endAnim();
  914. return false;
  915. }
  916. if(areaEffect) //f.e. armageddon
  917. {
  918. for(int i=0; i * first->width() < owner->pos.w ; ++i)
  919. {
  920. for(int j=0; j * first->height() < owner->pos.h ; ++j)
  921. {
  922. BattleEffect be;
  923. be.effectID = ID;
  924. be.animation = animation;
  925. be.currentFrame = 0;
  926. be.x = i * first->width() + owner->pos.x;
  927. be.y = j * first->height() + owner->pos.y;
  928. be.position = BattleHex::INVALID;
  929. owner->battleEffects.push_back(be);
  930. }
  931. }
  932. }
  933. else // Effects targeted at a specific creature/hex.
  934. {
  935. const CStack * destStack = owner->getCurrentPlayerInterface()->cb->battleGetStackByPos(destTile, false);
  936. BattleEffect be;
  937. be.effectID = ID;
  938. be.animation = animation;
  939. be.currentFrame = 0;
  940. //todo: lightning anim frame count override
  941. // if(effect == 1)
  942. // be.maxFrame = 3;
  943. be.x = x;
  944. be.y = y;
  945. if(destTile.isValid())
  946. {
  947. Rect & tilePos = owner->bfield[destTile]->pos;
  948. if(x == -1)
  949. be.x = tilePos.x + tilePos.w/2 - first->width()/2;
  950. if(y == -1)
  951. {
  952. if(alignToBottom)
  953. be.y = tilePos.y + tilePos.h - first->height();
  954. else
  955. be.y = tilePos.y - first->height()/2;
  956. }
  957. // Correction for 2-hex creatures.
  958. if(destStack != nullptr && destStack->doubleWide())
  959. be.x += (destStack->side == BattleSide::ATTACKER ? -1 : 1)*tilePos.w/2;
  960. }
  961. assert(be.x != -1 && be.y != -1);
  962. //Indicate if effect should be drawn on top of everything or just on top of the hex
  963. be.position = destTile;
  964. owner->battleEffects.push_back(be);
  965. }
  966. //battleEffects
  967. return true;
  968. }
  969. void CEffectAnimation::nextFrame()
  970. {
  971. //notice: there may be more than one effect in owner->battleEffects correcponding to this animation (ie. armageddon)
  972. for(auto & elem : owner->battleEffects)
  973. {
  974. if(elem.effectID == ID)
  975. {
  976. elem.currentFrame += AnimationControls::getSpellEffectSpeed() * GH.mainFPSmng->getElapsedMilliseconds() / 1000;
  977. if(elem.currentFrame >= elem.animation->size())
  978. {
  979. endAnim();
  980. break;
  981. }
  982. else
  983. {
  984. elem.x += dx;
  985. elem.y += dy;
  986. }
  987. }
  988. }
  989. }
  990. void CEffectAnimation::endAnim()
  991. {
  992. CBattleAnimation::endAnim();
  993. std::vector<std::list<BattleEffect>::iterator> toDel;
  994. for(auto it = owner->battleEffects.begin(); it != owner->battleEffects.end(); ++it)
  995. {
  996. if(it->effectID == ID)
  997. {
  998. toDel.push_back(it);
  999. }
  1000. }
  1001. for(auto & elem : toDel)
  1002. {
  1003. owner->battleEffects.erase(elem);
  1004. }
  1005. delete this;
  1006. }