CCreatureAnimation.cpp 12 KB

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