BsAnimation.h 17 KB

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