BsAnimation.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsCorePrerequisites.h"
  5. #include "BsCoreObject.h"
  6. #include "BsFlags.h"
  7. #include "BsSkeleton.h"
  8. #include "BsVector2.h"
  9. namespace BansheeEngine
  10. {
  11. /** @addtogroup Animation-Internal
  12. * @{
  13. */
  14. /** Determines how an animation clip behaves when it reaches the end. */
  15. enum class AnimWrapMode
  16. {
  17. Loop, /**< Loop around to the beginning/end when the last/first frame is reached. */
  18. Clamp /**< Clamp to end/beginning, keeping the last/first frame active. */
  19. };
  20. /** Flags that determine which portion of Animation was changed and needs to be updated. */
  21. enum class AnimDirtyStateFlag
  22. {
  23. Clean = 0,
  24. Value = 1 << 0,
  25. Layout = 1 << 1,
  26. Skeleton = 1 << 2
  27. };
  28. typedef Flags<AnimDirtyStateFlag> AnimDirtyState;
  29. BS_FLAGS_OPERATORS(AnimDirtyStateFlag)
  30. /** Contains information about a currently playing animation clip. */
  31. struct AnimationClipState
  32. {
  33. AnimationClipState() { }
  34. /** Layer the clip is playing on. Multiple clips can be played simulatenously on different layers. */
  35. UINT32 layer = 0;
  36. float time = 0.0f; /**< Current time the animation is playing from. */
  37. float speed = 1.0f; /**< Speed at which the animation is playing. */
  38. float weight = 1.0f; /**< Determines how much of an influence does the clip have on the final pose. */
  39. /** Determines what happens to other animation clips when a new clip starts playing. */
  40. AnimWrapMode wrapMode = AnimWrapMode::Loop;
  41. /**
  42. * Determines should the time be advanced automatically. Certain type of animation clips don't involve playback
  43. * (e.g. for blending where animation weight controls the animation).
  44. */
  45. bool stopped = false;
  46. };
  47. /** Internal information about a single playing animation clip within Animation. */
  48. struct AnimationClipInfo
  49. {
  50. AnimationClipInfo();
  51. AnimationClipInfo(const HAnimationClip& clip);
  52. HAnimationClip clip;
  53. AnimationClipState state;
  54. float fadeDirection;
  55. float fadeTime;
  56. float fadeLength;
  57. /**
  58. * Version of the animation curves used by the AnimationProxy. Used to detecting the internal animation curves
  59. * changed.
  60. */
  61. UINT64 curveVersion;
  62. UINT32 layerIdx; /**< Layer index this clip belongs to in AnimationProxy structure. */
  63. UINT32 stateIdx; /**< State index this clip belongs to in AnimationProxy structure. */
  64. };
  65. /** Represents an animation clip used in 1D blending. Each clip has a position on the number line. */
  66. struct BS_CORE_EXPORT BlendClipInfo
  67. {
  68. BlendClipInfo() { }
  69. HAnimationClip clip;
  70. float position = 0.0f;
  71. };
  72. /** Defines a 1D blend where multiple animation clips are blended between each other using linear interpolation. */
  73. struct BS_CORE_EXPORT Blend1DInfo
  74. {
  75. Blend1DInfo(UINT32 numClips);
  76. ~Blend1DInfo();
  77. UINT32 numClips;
  78. BlendClipInfo* clips;
  79. };
  80. /** Defines a 2D blend where two animation clips are blended between each other using bilinear interpolation. */
  81. struct Blend2DInfo
  82. {
  83. HAnimationClip topLeftClip;
  84. HAnimationClip topRightClip;
  85. HAnimationClip botLeftClip;
  86. HAnimationClip botRightClip;
  87. };
  88. /** Contains a mapping between a scene object and an animation curve it is animated with. */
  89. struct AnimatedSceneObject
  90. {
  91. HSceneObject so;
  92. String curveName;
  93. };
  94. /** Contains information about a scene object that is animated by a specific animation curve. */
  95. struct AnimatedSceneObjectInfo
  96. {
  97. UINT64 id; /**< Instance ID of the scene object. */
  98. INT32 boneIdx; /**< Bone from which to access the transform. If -1 then no bone mapping is present. */
  99. INT32 layerIdx; /**< If no bone mapping, layer on which the animation containing the referenced curve is in. */
  100. INT32 stateIdx; /**< If no bone mapping, animation state containing the referenced curve. */
  101. AnimationCurveMapping curveIndices; /**< Indices of the curves used for the transform. */
  102. UINT32 hash; /**< Hash value of the scene object's transform. */
  103. };
  104. /** Represents a copy of the Animation data for use specifically on the animation thread. */
  105. struct AnimationProxy
  106. {
  107. AnimationProxy(UINT64 id);
  108. AnimationProxy(const AnimationProxy&) = delete;
  109. ~AnimationProxy();
  110. AnimationProxy& operator=(const AnimationProxy&) = delete;
  111. /**
  112. * Rebuilds the internal proxy data according to the newly assigned skeleton and clips. This should be called
  113. * whenever the animation skeleton changes.
  114. *
  115. * @param[in] skeleton New skeleton to assign to the proxy.
  116. * @param[in, out] clipInfos Potentially new clip infos that will be used for rebuilding the proxy. Once the
  117. * method completes clip info layout and state indices will be populated for
  118. * further use in the update*() methods.
  119. * @param[in] sceneObjects A list of scene objects that are influenced by specific animation curves.
  120. *
  121. * @note Should be called from the sim thread when the caller is sure the animation thread is not using it.
  122. */
  123. void rebuild(const SPtr<Skeleton>& skeleton, Vector<AnimationClipInfo>& clipInfos,
  124. const Vector<AnimatedSceneObject>& sceneObjects);
  125. /**
  126. * Rebuilds the internal proxy data according to the newly clips. This should be called whenever clips are added
  127. * or removed, or clip layout indices change.
  128. *
  129. * @param[in, out] clipInfos New clip infos that will be used for rebuilding the proxy. Once the method
  130. * completes clip info layout and state indices will be populated for further use
  131. * in the update*() methods.
  132. * @param[in] sceneObjects A list of scene objects that are influenced by specific animation curves.
  133. *
  134. * @note Should be called from the sim thread when the caller is sure the animation thread is not using it.
  135. */
  136. void rebuild(Vector<AnimationClipInfo>& clipInfos, const Vector<AnimatedSceneObject>& sceneObjects);
  137. /**
  138. * Updates the proxy data with new information about the clips. Caller must guarantee that clip layout didn't
  139. * change since the last call to rebuild().
  140. *
  141. * @note Should be called from the sim thread when the caller is sure the animation thread is not using it.
  142. */
  143. void updateValues(const Vector<AnimationClipInfo>& clipInfos);
  144. /**
  145. * Updates the proxy data with new scene object transforms. Caller must guarantee that clip layout didn't
  146. * change since the last call to rebuild().
  147. *
  148. * @note Should be called from the sim thread when the caller is sure the animation thread is not using it.
  149. */
  150. void updateTransforms(const Vector<AnimatedSceneObject>& sceneObjects);
  151. /**
  152. * Updates the proxy data with new clip times. Caller must guarantee that clip layout didn't change since the last
  153. * call to rebuild().
  154. *
  155. * @note Should be called from the sim thread when the caller is sure the animation thread is not using it.
  156. */
  157. void updateTime(const Vector<AnimationClipInfo>& clipInfos);
  158. /** Destroys all dynamically allocated objects. */
  159. void clear();
  160. UINT64 id;
  161. AnimationStateLayer* layers;
  162. UINT32 numLayers;
  163. SPtr<Skeleton> skeleton;
  164. UINT32 numSceneObjects;
  165. AnimatedSceneObjectInfo* sceneObjectInfos;
  166. Matrix4* sceneObjectTransforms;
  167. // Evaluation results
  168. LocalSkeletonPose skeletonPose;
  169. LocalSkeletonPose sceneObjectPose;
  170. UINT32 numGenericCurves;
  171. float* genericCurveOutputs;
  172. };
  173. /**
  174. * Handles animation playback. Takes one or multiple animation clips as input and evaluates them every animation update
  175. * tick depending on set properties. The evaluated data is used by the core thread for skeletal animation, by the sim
  176. * thread for updating attached scene objects and bones (if skeleton is attached), or the data is made available for
  177. * manual queries in the case of generic animation.
  178. */
  179. class BS_CORE_EXPORT Animation : public CoreObject
  180. {
  181. public:
  182. ~Animation();
  183. /**
  184. * Changes the skeleton which will the translation/rotation/scale animation values manipulate. If no skeleton is set
  185. * the animation will only evaluate the generic curves, and the root translation/rotation/scale curves.
  186. */
  187. void setSkeleton(const SPtr<Skeleton>& skeleton);
  188. /**
  189. * Changes the wrap mode for all active animations. Wrap mode determines what happens when animation reaches the
  190. * first or last frame.
  191. *
  192. * @see AnimWrapMode
  193. */
  194. void setWrapMode(AnimWrapMode wrapMode);
  195. /** Changes the speed for all animations. The default value is 1.0f. Use negative values to play-back in reverse. */
  196. void setSpeed(float speed);
  197. /**
  198. * Plays the specified animation clip.
  199. *
  200. * @param[in] clip Clip to play.
  201. */
  202. void play(const HAnimationClip& clip);
  203. /**
  204. * Plays the specified animation clip on top of the animation currently playing in the main layer. Multiple
  205. * such clips can be playing at once, as long as you ensure each is given its own layer. Each animation can
  206. * also have a weight that determines how much it influences the main animation.
  207. *
  208. * @param[in] clip Clip to additively blend. Must contain additive animation curves.
  209. * @param[in] weight Determines how much of an effect will the blended animation have on the final output.
  210. * In range [0, 1].
  211. * @param[in] fadeLength Applies the blend over a specified time period, increasing the weight as the time
  212. * passes. Set to zero to blend immediately. In seconds.
  213. * @param[in] layer Layer to play the clip in. Multiple additive clips can be playing at once in separate
  214. * layers and each layer has its own weight.
  215. */
  216. void blendAdditive(const HAnimationClip& clip, float weight, float fadeLength = 0.0f, UINT32 layer = 0);
  217. /**
  218. * Blend multiple animation clips between each other using linear interpolation. Unlike normal animations these
  219. * animations are not advanced with the progress of time, and is instead expected the user manually changes the
  220. * @p t parameter.
  221. *
  222. * @param[in] info Information about the clips to blend. Clip positions must be sorted from lowest to highest.
  223. * @param[in] t Parameter that controls the blending. Range depends on the positions of the provided
  224. * animation clips.
  225. */
  226. void blend1D(const Blend1DInfo& info, float t);
  227. /**
  228. * Blend four animation clips between each other using bilinear interpolation. Unlike normal animations these
  229. * animations are not advanced with the progress of time, and is instead expected the user manually changes the
  230. * @p t parameter.
  231. *
  232. * @param[in] info Information about the clips to blend.
  233. * @param[in] t Parameter that controls the blending, in range [(0, 0), (1, 1)]. t = (0, 0) means top left
  234. * animation has full influence, t = (0, 1) means top right animation has full influence,
  235. * t = (1, 0) means bottom left animation has full influence, t = (1, 1) means bottom right
  236. * animation has full influence.
  237. */
  238. void blend2D(const Blend2DInfo& info, const Vector2& t);
  239. /**
  240. * Fades the specified animation clip in, while fading other playing animation out, over the specified time
  241. * period.
  242. *
  243. * @param[in] clip Clip to fade in.
  244. * @param[in] fadeLength Determines the time period over which the fade occurs. In seconds.
  245. */
  246. void crossFade(const HAnimationClip& clip, float fadeLength);
  247. /**
  248. * Stops playing all animations on the provided layer. Specify -1 to stop animation on the main layer
  249. * (non-additive animations).
  250. */
  251. void stop(UINT32 layer);
  252. /** Stops playing all animations. */
  253. void stopAll();
  254. /** Checks if any animation clips are currently playing. */
  255. bool isPlaying() const;
  256. /**
  257. * Retrieves detailed information about a currently playing animation clip.
  258. *
  259. * @param[in] clip Clip to retrieve the information for.
  260. * @param[out] state Animation clip state containing the requested information. Only valid if the method returns
  261. * true.
  262. * @return True if the state was found (animation clip is playing), false otherwise.
  263. */
  264. bool getState(const HAnimationClip& clip, AnimationClipState& state);
  265. /**
  266. * Changes the state of a playing animation clip. If animation clip is not currently playing the state change is
  267. * ignored.
  268. *
  269. * @param[in] clip Clip to change the state for.
  270. * @param[in] state New state of the animation (e.g. changing the time for seeking).
  271. */
  272. void setState(const HAnimationClip& clip, AnimationClipState state);
  273. /**
  274. * Ensures that any position/rotation/scale animation of a specific animation curve is transfered to the
  275. * the provided scene object. Also allow the opposite operation which can allow scene object transform changes
  276. * to manipulate object bones.
  277. *
  278. * @param[in] curve Name of the curve (bone) to connect the scene object with.
  279. * @param[in] so Scene object to influence by the curve modifications, and vice versa.
  280. */
  281. void mapCurveToSceneObject(const String& curve, const HSceneObject& so);
  282. /** Removes the curve <-> scene object mapping that was set via mapCurveToSceneObject(). */
  283. void unmapSceneObject(const HSceneObject& so);
  284. /**
  285. * Retrieves an evaluated value for a generic curve with the specified index.
  286. *
  287. * @param[in] curveIdx The curve index referencing a set of curves from the first playing animation clip.
  288. * Generic curves from all other clips are ignored.
  289. * @param[out] value Value of the generic curve. Only valid if the method return true.
  290. * @return True if the value was retrieved successfully. The method might fail if animation update
  291. * didn't yet have a chance to execute and values are not yet available, or if the
  292. * animation clip changed since the last frame (the last problem can be avoided by ensuring
  293. * to read the curve values before changing the clip).
  294. */
  295. bool getGenericCurveValue(UINT32 curveIdx, float& value);
  296. /** Creates a new empty Animation object. */
  297. static SPtr<Animation> create();
  298. /** Triggered whenever an animation event is reached. */
  299. Event<void(const HAnimationClip&, const String&)> onEventTriggered;
  300. /** @name Internal
  301. * @{
  302. */
  303. /** Returns the unique ID for this animation object. */
  304. UINT64 _getId() const { return mId; }
  305. /** @} */
  306. private:
  307. friend class AnimationManager;
  308. Animation();
  309. /**
  310. * Triggers any events between the last frame and current one.
  311. *
  312. * @param[in] lastFrameTime Time of the last frame.
  313. * @param[in] delta Difference between the last and this frame.
  314. */
  315. void triggerEvents(float lastFrameTime, float delta);
  316. /**
  317. * Updates the animation proxy object based on the currently set skeleton, playing clips and dirty flags.
  318. *
  319. * @param[in] timeDelta Seconds passed since the last call to this method.
  320. */
  321. void updateAnimProxy(float timeDelta);
  322. /**
  323. * Applies any outputs stored in the animation proxy (as written by the animation thread), and uses them to update
  324. * the animation state on the simulation thread. Caller must ensure that the animation thread has finished
  325. * with the animation proxy.
  326. */
  327. void updateFromProxy();
  328. /**
  329. * Registers a new animation in the specified layer, or returns an existing animation clip info if the animation is
  330. * already registered. If @p stopExisting is true any existing animations in the layer will be stopped. Layout
  331. * will be marked as dirty if any changes were made.
  332. */
  333. AnimationClipInfo* addClip(const HAnimationClip& clip, UINT32 layer, bool stopExisting = true);
  334. UINT64 mId;
  335. AnimWrapMode mDefaultWrapMode;
  336. float mDefaultSpeed;
  337. AnimDirtyState mDirty;
  338. SPtr<Skeleton> mSkeleton;
  339. Vector<AnimationClipInfo> mClipInfos;
  340. UnorderedMap<UINT64, AnimatedSceneObject> mSceneObjects;
  341. Vector<float> mGenericCurveOutputs;
  342. bool mGenericCurveValuesValid;
  343. // Animation thread only
  344. SPtr<AnimationProxy> mAnimProxy;
  345. };
  346. /** @} */
  347. }