CCreatureAnimation.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /*
  2. * CCreatureAnimation.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 "CCreatureAnimation.h"
  12. #include "../../lib/vcmi_endian.h"
  13. #include "../../lib/CConfigHandler.h"
  14. #include "../../lib/CCreatureHandler.h"
  15. #include "../../lib/filesystem/Filesystem.h"
  16. #include "../../lib/filesystem/CBinaryReader.h"
  17. #include "../../lib/filesystem/CMemoryStream.h"
  18. #include "../gui/SDL_Pixels.h"
  19. static const SDL_Color creatureBlueBorder = { 0, 255, 255, 255 };
  20. static const SDL_Color creatureGoldBorder = { 255, 255, 0, 255 };
  21. static const SDL_Color creatureNoBorder = { 0, 0, 0, 0 };
  22. SDL_Color AnimationControls::getBlueBorder()
  23. {
  24. return creatureBlueBorder;
  25. }
  26. SDL_Color AnimationControls::getGoldBorder()
  27. {
  28. return creatureGoldBorder;
  29. }
  30. SDL_Color AnimationControls::getNoBorder()
  31. {
  32. return creatureNoBorder;
  33. }
  34. CCreatureAnimation * AnimationControls::getAnimation(const CCreature * creature)
  35. {
  36. auto func = std::bind(&AnimationControls::getCreatureAnimationSpeed, creature, _1, _2);
  37. return new CCreatureAnimation(creature->animDefName, func);
  38. }
  39. float AnimationControls::getCreatureAnimationSpeed(const CCreature * creature, const CCreatureAnimation * anim, size_t group)
  40. {
  41. CCreatureAnim::EAnimType type = CCreatureAnim::EAnimType(group);
  42. assert(creature->animation.walkAnimationTime != 0);
  43. assert(creature->animation.attackAnimationTime != 0);
  44. assert(anim->framesInGroup(type) != 0);
  45. // possible new fields for creature format:
  46. //split "Attack time" into "Shoot Time" and "Cast Time"
  47. // a lot of arbitrary multipliers, mostly to make animation speed closer to H3
  48. const float baseSpeed = 0.1;
  49. const float speedMult = settings["battle"]["animationSpeed"].Float();
  50. const float speed = baseSpeed / speedMult;
  51. switch(type)
  52. {
  53. case CCreatureAnim::MOVING:
  54. return speed * 2 * creature->animation.walkAnimationTime / anim->framesInGroup(type);
  55. case CCreatureAnim::MOUSEON:
  56. return baseSpeed;
  57. case CCreatureAnim::HOLDING:
  58. return baseSpeed * creature->animation.idleAnimationTime / anim->framesInGroup(type);
  59. case CCreatureAnim::SHOOT_UP:
  60. case CCreatureAnim::SHOOT_FRONT:
  61. case CCreatureAnim::SHOOT_DOWN:
  62. case CCreatureAnim::CAST_UP:
  63. case CCreatureAnim::CAST_FRONT:
  64. case CCreatureAnim::CAST_DOWN:
  65. return speed * 4 * creature->animation.attackAnimationTime / anim->framesInGroup(type);
  66. // as strange as it looks like "attackAnimationTime" does not affects melee attacks
  67. // necessary because length of these animations must be same for all creatures for synchronization
  68. case CCreatureAnim::ATTACK_UP:
  69. case CCreatureAnim::ATTACK_FRONT:
  70. case CCreatureAnim::ATTACK_DOWN:
  71. case CCreatureAnim::HITTED:
  72. case CCreatureAnim::DEFENCE:
  73. case CCreatureAnim::DEATH:
  74. return speed * 3 / anim->framesInGroup(type);
  75. case CCreatureAnim::TURN_L:
  76. case CCreatureAnim::TURN_R:
  77. return speed / 3;
  78. case CCreatureAnim::MOVE_START:
  79. case CCreatureAnim::MOVE_END:
  80. return speed / 3;
  81. case CCreatureAnim::DEAD:
  82. return speed;
  83. default:
  84. assert(0);
  85. return 1;
  86. }
  87. }
  88. float AnimationControls::getProjectileSpeed()
  89. {
  90. return settings["battle"]["animationSpeed"].Float() * 100;
  91. }
  92. float AnimationControls::getSpellEffectSpeed()
  93. {
  94. return settings["battle"]["animationSpeed"].Float() * 60;
  95. }
  96. float AnimationControls::getMovementDuration(const CCreature * creature)
  97. {
  98. return settings["battle"]["animationSpeed"].Float() * 4 / creature->animation.walkAnimationTime;
  99. }
  100. float AnimationControls::getFlightDistance(const CCreature * creature)
  101. {
  102. return creature->animation.flightAnimationDistance * 200;
  103. }
  104. CCreatureAnim::EAnimType CCreatureAnimation::getType() const
  105. {
  106. return type;
  107. }
  108. void CCreatureAnimation::setType(CCreatureAnim::EAnimType type)
  109. {
  110. assert(type >= 0);
  111. assert(framesInGroup(type) != 0);
  112. this->type = type;
  113. currentFrame = 0;
  114. once = false;
  115. play();
  116. }
  117. CCreatureAnimation::CCreatureAnimation(std::string name, TSpeedController controller)
  118. : defName(name), speed(0.1), currentFrame(0), elapsedTime(0), type(CCreatureAnim::HOLDING), border(CSDL_Ext::makeColor(0, 0, 0, 0)), speedController(controller), once(false)
  119. {
  120. // separate block to avoid accidental use of "data" after it was moved into "pixelData"
  121. {
  122. ResourceID resID(std::string("SPRITES/") + name, EResType::ANIMATION);
  123. auto data = CResourceHandler::get()->load(resID)->readAll();
  124. pixelData = std::move(data.first);
  125. pixelDataSize = data.second;
  126. }
  127. CMemoryStream stm(pixelData.get(), pixelDataSize);
  128. CBinaryReader reader(&stm);
  129. reader.readInt32(); // def type, unused
  130. fullWidth = reader.readInt32();
  131. fullHeight = reader.readInt32();
  132. int totalBlocks = reader.readInt32();
  133. for(auto & elem : palette)
  134. {
  135. elem.r = reader.readUInt8();
  136. elem.g = reader.readUInt8();
  137. elem.b = reader.readUInt8();
  138. elem.a = SDL_ALPHA_OPAQUE;
  139. }
  140. for(int i = 0; i < totalBlocks; i++)
  141. {
  142. int groupID = reader.readInt32();
  143. int totalInBlock = reader.readInt32();
  144. reader.skip(4 + 4 + 13 * totalInBlock); // some unused data
  145. for(int j = 0; j < totalInBlock; j++)
  146. dataOffsets[groupID].push_back(reader.readUInt32());
  147. }
  148. // if necessary, add one frame into vcmi-only group DEAD
  149. if(dataOffsets.count(CCreatureAnim::DEAD) == 0)
  150. dataOffsets[CCreatureAnim::DEAD].push_back(dataOffsets[CCreatureAnim::DEATH].back());
  151. play();
  152. }
  153. void CCreatureAnimation::endAnimation()
  154. {
  155. once = false;
  156. auto copy = onAnimationReset;
  157. onAnimationReset.clear();
  158. copy();
  159. }
  160. bool CCreatureAnimation::incrementFrame(float timePassed)
  161. {
  162. elapsedTime += timePassed;
  163. currentFrame += timePassed * speed;
  164. if(currentFrame >= float(framesInGroup(type)))
  165. {
  166. // just in case of extremely low fps (or insanely high speed)
  167. while(currentFrame >= float(framesInGroup(type)))
  168. currentFrame -= framesInGroup(type);
  169. if(once)
  170. setType(CCreatureAnim::HOLDING);
  171. endAnimation();
  172. return true;
  173. }
  174. return false;
  175. }
  176. void CCreatureAnimation::setBorderColor(SDL_Color palette)
  177. {
  178. border = palette;
  179. }
  180. int CCreatureAnimation::getWidth() const
  181. {
  182. return fullWidth;
  183. }
  184. int CCreatureAnimation::getHeight() const
  185. {
  186. return fullHeight;
  187. }
  188. float CCreatureAnimation::getCurrentFrame() const
  189. {
  190. return currentFrame;
  191. }
  192. void CCreatureAnimation::playOnce(CCreatureAnim::EAnimType type)
  193. {
  194. setType(type);
  195. once = true;
  196. }
  197. inline int getBorderStrength(float time)
  198. {
  199. float borderStrength = fabs(vstd::round(time) - time) * 2; // generate value in range 0-1
  200. return borderStrength * 155 + 100; // scale to 0-255
  201. }
  202. static SDL_Color genShadow(ui8 alpha)
  203. {
  204. return CSDL_Ext::makeColor(0, 0, 0, alpha);
  205. }
  206. static SDL_Color genBorderColor(ui8 alpha, const SDL_Color & base)
  207. {
  208. return CSDL_Ext::makeColor(base.r, base.g, base.b, ui8(base.a * alpha / 256));
  209. }
  210. static ui8 mixChannels(ui8 c1, ui8 c2, ui8 a1, ui8 a2)
  211. {
  212. return c1 * a1 / 256 + c2 * a2 * (255 - a1) / 256 / 256;
  213. }
  214. static SDL_Color addColors(const SDL_Color & base, const SDL_Color & over)
  215. {
  216. return CSDL_Ext::makeColor(
  217. mixChannels(over.r, base.r, over.a, base.a),
  218. mixChannels(over.g, base.g, over.a, base.a),
  219. mixChannels(over.b, base.b, over.a, base.a),
  220. ui8(over.a + base.a * (255 - over.a) / 256)
  221. );
  222. }
  223. std::array<SDL_Color, 8> CCreatureAnimation::genSpecialPalette()
  224. {
  225. std::array<SDL_Color, 8> ret;
  226. ret[0] = genShadow(0);
  227. ret[1] = genShadow(64);
  228. ret[2] = genShadow(128);
  229. ret[3] = genShadow(128);
  230. ret[4] = genShadow(128);
  231. ret[5] = genBorderColor(getBorderStrength(elapsedTime), border);
  232. ret[6] = addColors(genShadow(128), genBorderColor(getBorderStrength(elapsedTime), border));
  233. ret[7] = addColors(genShadow(64), genBorderColor(getBorderStrength(elapsedTime), border));
  234. return ret;
  235. }
  236. template<int bpp>
  237. void CCreatureAnimation::nextFrameT(SDL_Surface * dest, bool rotate)
  238. {
  239. assert(dataOffsets.count(type) && dataOffsets.at(type).size() > size_t(currentFrame));
  240. ui32 offset = dataOffsets.at(type).at(floor(currentFrame));
  241. CMemoryStream stm(pixelData.get(), pixelDataSize);
  242. CBinaryReader reader(&stm);
  243. reader.getStream()->seek(offset);
  244. reader.readUInt32(); // unused, size of pixel data for this frame
  245. const ui32 defType2 = reader.readUInt32();
  246. const ui32 fullWidth = reader.readUInt32();
  247. /*const ui32 fullHeight =*/ reader.readUInt32();
  248. const ui32 spriteWidth = reader.readUInt32();
  249. const ui32 spriteHeight = reader.readUInt32();
  250. const int leftMargin = reader.readInt32();
  251. const int topMargin = reader.readInt32();
  252. const int rightMargin = fullWidth - spriteWidth - leftMargin;
  253. //const int bottomMargin = fullHeight - spriteHeight - topMargin;
  254. const size_t baseOffset = reader.getStream()->tell();
  255. assert(defType2 == 1);
  256. UNUSED(defType2);
  257. auto specialPalette = genSpecialPalette();
  258. for(ui32 i = 0; i < spriteHeight; i++)
  259. {
  260. //NOTE: if this loop will be optimized to skip empty lines - recheck this read access
  261. ui8 * lineData = pixelData.get() + baseOffset + reader.readUInt32();
  262. size_t destX = pos.x;
  263. if(rotate)
  264. destX += rightMargin + spriteWidth - 1;
  265. else
  266. destX += leftMargin;
  267. size_t destY = pos.y + topMargin + i;
  268. size_t currentOffset = 0;
  269. size_t totalRowLength = 0;
  270. while(totalRowLength < spriteWidth)
  271. {
  272. ui8 type = lineData[currentOffset++];
  273. ui32 length = lineData[currentOffset++] + 1;
  274. if(type == 0xFF) //Raw data
  275. {
  276. for(size_t j = 0; j < length; j++)
  277. putPixelAt<bpp>(dest, destX + (rotate ? (-j) : (j)), destY, lineData[currentOffset + j], specialPalette);
  278. currentOffset += length;
  279. }
  280. else // RLE
  281. {
  282. if(type != 0) // transparency row, handle it here for speed
  283. {
  284. for(size_t j = 0; j < length; j++)
  285. putPixelAt<bpp>(dest, destX + (rotate ? (-j) : (j)), destY, type, specialPalette);
  286. }
  287. }
  288. destX += rotate ? (-length) : (length);
  289. totalRowLength += length;
  290. }
  291. }
  292. }
  293. void CCreatureAnimation::nextFrame(SDL_Surface * dest, bool attacker)
  294. {
  295. // Note: please notice that attacker value is inversed when passed further.
  296. // This is intended behavior because "attacker" actually does not needs rotation
  297. switch(dest->format->BytesPerPixel)
  298. {
  299. case 2:
  300. return nextFrameT<2>(dest, !attacker);
  301. case 3:
  302. return nextFrameT<3>(dest, !attacker);
  303. case 4:
  304. return nextFrameT<4>(dest, !attacker);
  305. default:
  306. logGlobal->errorStream() << (int)dest->format->BitsPerPixel << " bpp is not supported!!!";
  307. }
  308. }
  309. int CCreatureAnimation::framesInGroup(CCreatureAnim::EAnimType group) const
  310. {
  311. if(dataOffsets.count(group) == 0)
  312. return 0;
  313. return dataOffsets.at(group).size();
  314. }
  315. ui8 * CCreatureAnimation::getPixelAddr(SDL_Surface * dest, int X, int Y) const
  316. {
  317. return (ui8 *)dest->pixels + X * dest->format->BytesPerPixel + Y * dest->pitch;
  318. }
  319. template<int bpp>
  320. inline void CCreatureAnimation::putPixelAt(SDL_Surface * dest, int X, int Y, size_t index, const std::array<SDL_Color, 8> & special) const
  321. {
  322. if(X < pos.x + pos.w && Y < pos.y + pos.h && X >= 0 && Y >= 0)
  323. putPixel<bpp>(getPixelAddr(dest, X, Y), palette[index], index, special);
  324. }
  325. template<int bpp>
  326. inline void CCreatureAnimation::putPixel(ui8 * dest, const SDL_Color & color, size_t index, const std::array<SDL_Color, 8> & special) const
  327. {
  328. if(index < 8)
  329. {
  330. const SDL_Color & pal = special[index];
  331. ColorPutter<bpp, 0>::PutColor(dest, pal.r, pal.g, pal.b, pal.a);
  332. }
  333. else
  334. {
  335. ColorPutter<bpp, 0>::PutColor(dest, color.r, color.g, color.b);
  336. }
  337. }
  338. bool CCreatureAnimation::isDead() const
  339. {
  340. return getType() == CCreatureAnim::DEAD
  341. || getType() == CCreatureAnim::DEATH;
  342. }
  343. bool CCreatureAnimation::isIdle() const
  344. {
  345. return getType() == CCreatureAnim::HOLDING
  346. || getType() == CCreatureAnim::MOUSEON;
  347. }
  348. bool CCreatureAnimation::isMoving() const
  349. {
  350. return getType() == CCreatureAnim::MOVE_START
  351. || getType() == CCreatureAnim::MOVING
  352. || getType() == CCreatureAnim::MOVE_END;
  353. }
  354. bool CCreatureAnimation::isShooting() const
  355. {
  356. return getType() == CCreatureAnim::SHOOT_UP
  357. || getType() == CCreatureAnim::SHOOT_FRONT
  358. || getType() == CCreatureAnim::SHOOT_DOWN;
  359. }
  360. void CCreatureAnimation::pause()
  361. {
  362. speed = 0;
  363. }
  364. void CCreatureAnimation::play()
  365. {
  366. speed = 0;
  367. if(speedController(this, type) != 0)
  368. speed = 1 / speedController(this, type);
  369. }