CCreatureAnimation.cpp 13 KB

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