BsAnimationManager.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsAnimationManager.h"
  4. #include "BsAnimation.h"
  5. #include "BsAnimationClip.h"
  6. #include "BsTaskScheduler.h"
  7. #include "BsTime.h"
  8. #include "BsCoreSceneManager.h"
  9. #include "BsCamera.h"
  10. namespace BansheeEngine
  11. {
  12. AnimationManager::AnimationManager()
  13. : mNextId(1), mUpdateRate(1.0f / 60.0f), mAnimationTime(0.0f), mLastAnimationUpdateTime(0.0f)
  14. , mNextAnimationUpdateTime(0.0f), mPaused(false), mWorkerRunning(false), mPoseReadBufferIdx(0)
  15. , mPoseWriteBufferIdx(0), mDataReadyCount(0)
  16. {
  17. mAnimationWorker = Task::create("Animation", std::bind(&AnimationManager::evaluateAnimation, this));
  18. }
  19. void AnimationManager::setPaused(bool paused)
  20. {
  21. mPaused = paused;
  22. }
  23. void AnimationManager::setUpdateRate(UINT32 fps)
  24. {
  25. if (fps == 0)
  26. fps = 1;
  27. mUpdateRate = 1.0f / fps;
  28. }
  29. void AnimationManager::preUpdate()
  30. {
  31. if (mPaused || !mWorkerRunning)
  32. return;
  33. mAnimationWorker->wait();
  34. // Make sure we don't load obsolete skeletal pose and other evaluation ouputs written by the animation thread
  35. std::atomic_thread_fence(std::memory_order_acquire);
  36. // Trigger events
  37. for (auto& anim : mAnimations)
  38. {
  39. anim.second->updateFromProxy();
  40. anim.second->triggerEvents(mAnimationTime, gTime().getFrameDelta());
  41. }
  42. mWorkerRunning = false;
  43. }
  44. void AnimationManager::postUpdate()
  45. {
  46. if (mPaused)
  47. return;
  48. mAnimationTime += gTime().getFrameDelta();
  49. if (mAnimationTime < mNextAnimationUpdateTime)
  50. return;
  51. mNextAnimationUpdateTime = Math::floor(mAnimationTime / mUpdateRate) * mUpdateRate + mUpdateRate;
  52. float timeDelta = mAnimationTime - mLastAnimationUpdateTime;
  53. mLastAnimationUpdateTime = mAnimationTime;
  54. // Update poses in the currently active buffer. Multi-buffering allows the core thread to safely read the
  55. // poses without worrying about them being overwritten by another call to postUpdate, as long as the simulation
  56. // thread doesn't go more than (CoreThread::NUM_SYNC_BUFFERS - 1) frames ahead.
  57. mProxies.clear();
  58. for (auto& anim : mAnimations)
  59. {
  60. anim.second->updateAnimProxy(timeDelta);
  61. mProxies.push_back(anim.second->mAnimProxy);
  62. }
  63. mCullFrustums.clear();
  64. auto& allCameras = gCoreSceneManager().getAllCameras();
  65. for(auto& entry : allCameras)
  66. {
  67. bool isOverlayCamera = entry.second.camera->getFlags().isSet(CameraFlag::Overlay);
  68. if (isOverlayCamera)
  69. continue;
  70. // TODO: Not checking if camera and animation renderable's layers match. If we checked more animations could
  71. // be culled.
  72. mCullFrustums.push_back(entry.second.camera->getWorldFrustum());
  73. }
  74. // Make sure thread finishes writing all changes to the anim proxies as they will be read by the animation thread
  75. std::atomic_thread_fence(std::memory_order_release);
  76. // Note: Animation thread will trigger about the same time as the core thread. The core thread will need to wait
  77. // until animation thread finishes, which might end up blocking it (and losing the multi-threading performance).
  78. // Consider delaying displayed animation for a single frame or pre-calculating animations (by advancing time the
  79. // previous frame) for non-dirty animations.
  80. TaskScheduler::instance().addTask(mAnimationWorker);
  81. mWorkerRunning = true;
  82. }
  83. void AnimationManager::evaluateAnimation()
  84. {
  85. // Make sure we don't load obsolete anim proxy data written by the simulation thread
  86. std::atomic_thread_fence(std::memory_order_acquire);
  87. // No need for locking, as we are sure that only postUpdate() writes to the proxy buffer, and increments the write
  88. // buffer index. And it's called sequentially ensuring previous call to evaluate finishes.
  89. UINT32 totalNumBones = 0;
  90. for (auto& anim : mProxies)
  91. {
  92. if (anim->skeleton != nullptr)
  93. totalNumBones += anim->skeleton->getNumBones();
  94. }
  95. RendererAnimationData& renderData = mAnimData[mPoseWriteBufferIdx];
  96. mPoseWriteBufferIdx = (mPoseWriteBufferIdx + 1) % CoreThread::NUM_SYNC_BUFFERS;
  97. renderData.poseInfos.clear();
  98. renderData.transforms.resize(totalNumBones);
  99. UINT32 curBoneIdx = 0;
  100. for(auto& anim : mProxies)
  101. {
  102. if(anim->mCullEnabled)
  103. {
  104. bool isVisible = false;
  105. for(auto& frustum : mCullFrustums)
  106. {
  107. if(frustum.intersects(anim->mBounds))
  108. {
  109. isVisible = true;
  110. break;
  111. }
  112. }
  113. if (!isVisible)
  114. continue;
  115. }
  116. if (anim->skeleton != nullptr)
  117. {
  118. UINT32 numBones = anim->skeleton->getNumBones();
  119. RendererAnimationData::PoseInfo info;
  120. info.animId = anim->id;
  121. info.startIdx = curBoneIdx;
  122. info.numBones = numBones;
  123. Matrix4* boneDst = renderData.transforms.data() + curBoneIdx;
  124. // Copy transforms from mapped scene objects
  125. UINT32 boneTfrmIdx = 0;
  126. for(UINT32 i = 0; i < anim->numSceneObjects; i++)
  127. {
  128. const AnimatedSceneObjectInfo& soInfo = anim->sceneObjectInfos[i];
  129. if (soInfo.boneIdx == -1)
  130. continue;
  131. boneDst[soInfo.boneIdx] = anim->sceneObjectTransforms[boneTfrmIdx];
  132. boneTfrmIdx++;
  133. }
  134. // Animate bones
  135. anim->skeleton->getPose(boneDst, anim->skeletonPose, anim->skeletonMask, anim->layers, anim->numLayers);
  136. renderData.poseInfos[anim->id] = info;
  137. curBoneIdx += numBones;
  138. }
  139. // Reset mapped SO transform
  140. for (UINT32 i = 0; i < anim->sceneObjectPose.numBones; i++)
  141. {
  142. anim->sceneObjectPose.positions[i] = Vector3::ZERO;
  143. anim->sceneObjectPose.rotations[i] = Quaternion::IDENTITY;
  144. anim->sceneObjectPose.scales[i] = Vector3::ONE;
  145. }
  146. // Update mapped scene objects
  147. for(UINT32 i = 0; i < anim->numSceneObjects; i++)
  148. {
  149. const AnimatedSceneObjectInfo& soInfo = anim->sceneObjectInfos[i];
  150. // We already evaluated bones
  151. if (soInfo.boneIdx != -1)
  152. continue;
  153. const AnimationState& state = anim->layers[soInfo.layerIdx].states[soInfo.stateIdx];
  154. if (state.disabled)
  155. continue;
  156. {
  157. UINT32 curveIdx = soInfo.curveIndices.position;
  158. if (curveIdx != (UINT32)-1)
  159. {
  160. const TAnimationCurve<Vector3>& curve = state.curves->position[curveIdx].curve;
  161. anim->sceneObjectPose.positions[curveIdx] = curve.evaluate(state.time, state.positionCaches[curveIdx], state.loop);
  162. }
  163. }
  164. {
  165. UINT32 curveIdx = soInfo.curveIndices.rotation;
  166. if (curveIdx != (UINT32)-1)
  167. {
  168. const TAnimationCurve<Quaternion>& curve = state.curves->rotation[curveIdx].curve;
  169. anim->sceneObjectPose.rotations[curveIdx] = curve.evaluate(state.time, state.rotationCaches[curveIdx], state.loop);
  170. anim->sceneObjectPose.rotations[curveIdx].normalize();
  171. }
  172. }
  173. {
  174. UINT32 curveIdx = soInfo.curveIndices.scale;
  175. if (curveIdx != (UINT32)-1)
  176. {
  177. const TAnimationCurve<Vector3>& curve = state.curves->scale[curveIdx].curve;
  178. anim->sceneObjectPose.scales[curveIdx] = curve.evaluate(state.time, state.scaleCaches[curveIdx], state.loop);
  179. }
  180. }
  181. }
  182. // Note: No blending for generic animations, just use first animation
  183. if (anim->numLayers > 0 && anim->layers[0].numStates > 0)
  184. {
  185. const AnimationState& state = anim->layers[0].states[0];
  186. if (state.disabled)
  187. continue;
  188. {
  189. UINT32 numCurves = (UINT32)state.curves->generic.size();
  190. for (UINT32 i = 0; i < numCurves; i++)
  191. {
  192. const TAnimationCurve<float>& curve = state.curves->generic[i].curve;
  193. anim->genericCurveOutputs[i] = curve.evaluate(state.time, state.genericCaches[i], state.loop);
  194. }
  195. }
  196. }
  197. }
  198. mDataReadyCount.fetch_add(1, std::memory_order_relaxed);
  199. // Make sure the thread finishes writing skeletal pose and other evaluation outputs as they will be read by sim and
  200. // core threads
  201. std::atomic_thread_fence(std::memory_order_release);
  202. }
  203. const RendererAnimationData& AnimationManager::getRendererData()
  204. {
  205. mAnimationWorker->wait();
  206. // Make sure we don't load obsolete skeletal pose and other evaluation ouputs written by the animation thread
  207. std::atomic_thread_fence(std::memory_order_acquire);
  208. INT32 dataReadyCount = mDataReadyCount.load(std::memory_order_relaxed);
  209. assert(dataReadyCount <= CoreThread::NUM_SYNC_BUFFERS);
  210. if (dataReadyCount <= 0)
  211. {
  212. static RendererAnimationData dummy;
  213. return dummy;
  214. }
  215. const RendererAnimationData& output = mAnimData[mPoseReadBufferIdx];
  216. mPoseReadBufferIdx = (mPoseReadBufferIdx + 1) % CoreThread::NUM_SYNC_BUFFERS;
  217. mDataReadyCount.fetch_add(-1, std::memory_order_relaxed);
  218. return output;
  219. }
  220. UINT64 AnimationManager::registerAnimation(Animation* anim)
  221. {
  222. mAnimations[mNextId] = anim;
  223. return mNextId++;
  224. }
  225. void AnimationManager::unregisterAnimation(UINT64 animId)
  226. {
  227. mAnimations.erase(animId);
  228. }
  229. AnimationManager& gAnimation()
  230. {
  231. return AnimationManager::instance();
  232. }
  233. }