BsAnimation.h 20 KB

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