BsAnimationManager.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "Animation/BsAnimationManager.h"
  4. #include "Animation/BsAnimation.h"
  5. #include "Animation/BsAnimationClip.h"
  6. #include "Threading/BsTaskScheduler.h"
  7. #include "Utility/BsTime.h"
  8. #include "Scene/BsSceneManager.h"
  9. #include "Renderer/BsCamera.h"
  10. #include "Animation/BsMorphShapes.h"
  11. #include "Mesh/BsMeshData.h"
  12. #include "Mesh/BsMeshUtility.h"
  13. namespace bs
  14. {
  15. AnimationManager::AnimationManager()
  16. : mNextId(1), mUpdateRate(1.0f / 60.0f), mAnimationTime(0.0f), mLastAnimationUpdateTime(0.0f)
  17. , mNextAnimationUpdateTime(0.0f), mPaused(false), mWorkerStarted(false), mPoseReadBufferIdx(1)
  18. , mPoseWriteBufferIdx(0), mDataReady(false)
  19. {
  20. mAnimationWorker = Task::create("Animation", std::bind(&AnimationManager::evaluateAnimation, this));
  21. mDataReadyCount.store(0, std::memory_order_release);
  22. mWorkerState.store(WorkerState::Inactive, std::memory_order_release);
  23. mBlendShapeVertexDesc = VertexDataDesc::create();
  24. mBlendShapeVertexDesc->addVertElem(VET_FLOAT3, VES_POSITION, 1, 1);
  25. mBlendShapeVertexDesc->addVertElem(VET_UBYTE4_NORM, VES_NORMAL, 1, 1);
  26. }
  27. void AnimationManager::setPaused(bool paused)
  28. {
  29. mPaused = paused;
  30. }
  31. void AnimationManager::setUpdateRate(UINT32 fps)
  32. {
  33. if (fps == 0)
  34. fps = 1;
  35. mUpdateRate = 1.0f / fps;
  36. }
  37. void AnimationManager::preUpdate()
  38. {
  39. if (mPaused || !mWorkerStarted)
  40. return;
  41. mAnimationWorker->wait();
  42. WorkerState state = mWorkerState.load(std::memory_order_acquire);
  43. assert(state == WorkerState::DataReady);
  44. // Trigger events
  45. for (auto& anim : mAnimations)
  46. {
  47. anim.second->updateFromProxy();
  48. anim.second->triggerEvents(mAnimationTime, gTime().getFrameDelta());
  49. }
  50. }
  51. void AnimationManager::postUpdate()
  52. {
  53. if (mPaused)
  54. return;
  55. mAnimationTime += gTime().getFrameDelta();
  56. if (mAnimationTime < mNextAnimationUpdateTime)
  57. return;
  58. mNextAnimationUpdateTime = Math::floor(mAnimationTime / mUpdateRate) * mUpdateRate + mUpdateRate;
  59. float timeDelta = mAnimationTime - mLastAnimationUpdateTime;
  60. mLastAnimationUpdateTime = mAnimationTime;
  61. // Update poses in the currently active buffer. Multi-buffering allows the core thread to safely read the
  62. // poses without worrying about them being overwritten by another call to postUpdate, as long as the simulation
  63. // thread doesn't go more than (CoreThread::NUM_SYNC_BUFFERS - 1) frames ahead.
  64. mProxies.clear();
  65. for (auto& anim : mAnimations)
  66. {
  67. anim.second->updateAnimProxy(timeDelta);
  68. mProxies.push_back(anim.second->mAnimProxy);
  69. }
  70. mCullFrustums.clear();
  71. auto& allCameras = gSceneManager().getAllCameras();
  72. for(auto& entry : allCameras)
  73. {
  74. bool isOverlayCamera = entry.second->getRenderSettings()->overlayOnly;
  75. if (isOverlayCamera)
  76. continue;
  77. // TODO: Not checking if camera and animation renderable's layers match. If we checked more animations could
  78. // be culled.
  79. mCullFrustums.push_back(entry.second->getWorldFrustum());
  80. }
  81. // Make sure thread finishes writing all changes to the anim proxies as they will be read by the animation thread
  82. mWorkerStarted = true;
  83. mWorkerState.store(WorkerState::Started, std::memory_order_release);
  84. // Note: Animation thread will trigger about the same time as the core thread. The core thread will need to wait
  85. // until animation thread finishes, which might end up blocking it (and losing the multi-threading performance).
  86. // Consider delaying displayed animation for a single frame or pre-calculating animations (by advancing time the
  87. // previous frame) for non-dirty animations.
  88. TaskScheduler::instance().addTask(mAnimationWorker);
  89. }
  90. void AnimationManager::evaluateAnimation()
  91. {
  92. // Make sure we don't load obsolete anim proxy data written by the simulation thread
  93. WorkerState state = mWorkerState.load(std::memory_order_acquire);
  94. assert(state == WorkerState::Started);
  95. // No need for locking, as we are sure that only postUpdate() writes to the proxy buffer, and increments the write
  96. // buffer index. And it's called sequentially ensuring previous call to evaluate finishes.
  97. UINT32 totalNumBones = 0;
  98. for (auto& anim : mProxies)
  99. {
  100. if (anim->skeleton != nullptr)
  101. totalNumBones += anim->skeleton->getNumBones();
  102. }
  103. RendererAnimationData& renderData = mAnimData[mPoseWriteBufferIdx];
  104. UINT32 prevPoseBufferIdx = (mPoseWriteBufferIdx + CoreThread::NUM_SYNC_BUFFERS - 1) % CoreThread::NUM_SYNC_BUFFERS;
  105. RendererAnimationData& prevRenderData = mAnimData[prevPoseBufferIdx];
  106. mPoseWriteBufferIdx = (mPoseWriteBufferIdx + 1) % CoreThread::NUM_SYNC_BUFFERS;
  107. renderData.transforms.resize(totalNumBones);
  108. renderData.infos.clear();
  109. UINT32 curBoneIdx = 0;
  110. for(auto& anim : mProxies)
  111. {
  112. if(anim->mCullEnabled)
  113. {
  114. bool isVisible = false;
  115. for(auto& frustum : mCullFrustums)
  116. {
  117. if(frustum.intersects(anim->mBounds))
  118. {
  119. isVisible = true;
  120. break;
  121. }
  122. }
  123. if (!isVisible)
  124. continue;
  125. }
  126. RendererAnimationData::AnimInfo animInfo;
  127. bool hasAnimInfo = false;
  128. // Evaluate skeletal animation
  129. if (anim->skeleton != nullptr)
  130. {
  131. UINT32 numBones = anim->skeleton->getNumBones();
  132. RendererAnimationData::PoseInfo& poseInfo = animInfo.poseInfo;
  133. poseInfo.animId = anim->id;
  134. poseInfo.startIdx = curBoneIdx;
  135. poseInfo.numBones = numBones;
  136. memset(anim->skeletonPose.hasOverride, 0, sizeof(bool) * anim->skeletonPose.numBones);
  137. Matrix4* boneDst = renderData.transforms.data() + curBoneIdx;
  138. // Copy transforms from mapped scene objects
  139. UINT32 boneTfrmIdx = 0;
  140. for(UINT32 i = 0; i < anim->numSceneObjects; i++)
  141. {
  142. const AnimatedSceneObjectInfo& soInfo = anim->sceneObjectInfos[i];
  143. if (soInfo.boneIdx == -1)
  144. continue;
  145. boneDst[soInfo.boneIdx] = anim->sceneObjectTransforms[boneTfrmIdx];
  146. anim->skeletonPose.hasOverride[soInfo.boneIdx] = true;
  147. boneTfrmIdx++;
  148. }
  149. // Animate bones
  150. anim->skeleton->getPose(boneDst, anim->skeletonPose, anim->skeletonMask, anim->layers, anim->numLayers);
  151. curBoneIdx += numBones;
  152. hasAnimInfo = true;
  153. }
  154. else
  155. {
  156. RendererAnimationData::PoseInfo& poseInfo = animInfo.poseInfo;
  157. poseInfo.animId = anim->id;
  158. poseInfo.startIdx = 0;
  159. poseInfo.numBones = 0;
  160. }
  161. // Reset mapped SO transform
  162. for (UINT32 i = 0; i < anim->sceneObjectPose.numBones; i++)
  163. {
  164. anim->sceneObjectPose.positions[i] = Vector3::ZERO;
  165. anim->sceneObjectPose.rotations[i] = Quaternion::IDENTITY;
  166. anim->sceneObjectPose.scales[i] = Vector3::ONE;
  167. }
  168. // Update mapped scene objects
  169. memset(anim->sceneObjectPose.hasOverride, 1, sizeof(bool) * anim->numSceneObjects);
  170. // Update scene object transforms
  171. for(UINT32 i = 0; i < anim->numSceneObjects; i++)
  172. {
  173. const AnimatedSceneObjectInfo& soInfo = anim->sceneObjectInfos[i];
  174. // We already evaluated bones
  175. if (soInfo.boneIdx != -1)
  176. continue;
  177. if (soInfo.layerIdx == -1 || soInfo.stateIdx == -1)
  178. continue;
  179. const AnimationState& state = anim->layers[soInfo.layerIdx].states[soInfo.stateIdx];
  180. if (state.disabled)
  181. continue;
  182. {
  183. UINT32 curveIdx = soInfo.curveIndices.position;
  184. if (curveIdx != (UINT32)-1)
  185. {
  186. const TAnimationCurve<Vector3>& curve = state.curves->position[curveIdx].curve;
  187. anim->sceneObjectPose.positions[curveIdx] = curve.evaluate(state.time, state.positionCaches[curveIdx], state.loop);
  188. anim->sceneObjectPose.hasOverride[curveIdx] = false;
  189. }
  190. }
  191. {
  192. UINT32 curveIdx = soInfo.curveIndices.rotation;
  193. if (curveIdx != (UINT32)-1)
  194. {
  195. const TAnimationCurve<Quaternion>& curve = state.curves->rotation[curveIdx].curve;
  196. anim->sceneObjectPose.rotations[curveIdx] = curve.evaluate(state.time, state.rotationCaches[curveIdx], state.loop);
  197. anim->sceneObjectPose.rotations[curveIdx].normalize();
  198. anim->sceneObjectPose.hasOverride[curveIdx] = false;
  199. }
  200. }
  201. {
  202. UINT32 curveIdx = soInfo.curveIndices.scale;
  203. if (curveIdx != (UINT32)-1)
  204. {
  205. const TAnimationCurve<Vector3>& curve = state.curves->scale[curveIdx].curve;
  206. anim->sceneObjectPose.scales[curveIdx] = curve.evaluate(state.time, state.scaleCaches[curveIdx], state.loop);
  207. anim->sceneObjectPose.hasOverride[curveIdx] = false;
  208. }
  209. }
  210. }
  211. // Update generic curves
  212. // Note: No blending for generic animations, just use first animation
  213. if (anim->numLayers > 0 && anim->layers[0].numStates > 0)
  214. {
  215. const AnimationState& state = anim->layers[0].states[0];
  216. if (!state.disabled)
  217. {
  218. UINT32 numCurves = (UINT32)state.curves->generic.size();
  219. for (UINT32 i = 0; i < numCurves; i++)
  220. {
  221. const TAnimationCurve<float>& curve = state.curves->generic[i].curve;
  222. anim->genericCurveOutputs[i] = curve.evaluate(state.time, state.genericCaches[i], state.loop);
  223. }
  224. }
  225. }
  226. // Update morph shapes
  227. if(anim->numMorphShapes > 0)
  228. {
  229. auto iterFind = prevRenderData.infos.find(anim->id);
  230. if (iterFind != prevRenderData.infos.end())
  231. animInfo.morphShapeInfo = iterFind->second.morphShapeInfo;
  232. else
  233. animInfo.morphShapeInfo.version = 1; // 0 is considered invalid version
  234. // Recalculate weights if curves are present
  235. bool hasMorphCurves = false;
  236. for(UINT32 i = 0; i < anim->numMorphChannels; i++)
  237. {
  238. MorphChannelInfo& channelInfo = anim->morphChannelInfos[i];
  239. if(channelInfo.weightCurveIdx != (UINT32)-1)
  240. {
  241. channelInfo.weight = Math::clamp01(anim->genericCurveOutputs[channelInfo.weightCurveIdx]);
  242. hasMorphCurves = true;
  243. }
  244. float frameWeight;
  245. if (channelInfo.frameCurveIdx != (UINT32)-1)
  246. {
  247. frameWeight = Math::clamp01(anim->genericCurveOutputs[channelInfo.frameCurveIdx]);
  248. hasMorphCurves = true;
  249. }
  250. else
  251. frameWeight = 0.0f;
  252. if(channelInfo.shapeCount == 1)
  253. {
  254. MorphShapeInfo& shapeInfo = anim->morphShapeInfos[channelInfo.shapeStart];
  255. // Blend between base shape and the only available frame
  256. float relative = frameWeight - shapeInfo.frameWeight;
  257. if (relative <= 0.0f)
  258. {
  259. float diff = shapeInfo.frameWeight;
  260. if (diff > 0.0f)
  261. {
  262. float t = -relative / diff;
  263. shapeInfo.finalWeight = 1.0f - std::min(t, 1.0f);
  264. }
  265. else
  266. shapeInfo.finalWeight = 1.0f;
  267. }
  268. else // If past the final frame we clamp
  269. shapeInfo.finalWeight = 1.0f;
  270. }
  271. else if(channelInfo.shapeCount > 1)
  272. {
  273. for(UINT32 j = 0; j < channelInfo.shapeCount - 1; j++)
  274. {
  275. float prevShapeWeight;
  276. if (j > 0)
  277. prevShapeWeight = anim->morphShapeInfos[j - 1].frameWeight;
  278. else
  279. prevShapeWeight = 0.0f; // Base shape, blend between it and the first frame
  280. float nextShapeWeight = anim->morphShapeInfos[j + 1].frameWeight;
  281. MorphShapeInfo& shapeInfo = anim->morphShapeInfos[j];
  282. float relative = frameWeight - shapeInfo.frameWeight;
  283. if (relative <= 0.0f)
  284. {
  285. float diff = shapeInfo.frameWeight - prevShapeWeight;
  286. if (diff > 0.0f)
  287. {
  288. float t = -relative / diff;
  289. shapeInfo.finalWeight = 1.0f - std::min(t, 1.0f);
  290. }
  291. else
  292. shapeInfo.finalWeight = 1.0f;
  293. }
  294. else
  295. {
  296. float diff = nextShapeWeight - shapeInfo.frameWeight;
  297. if (diff > 0.0f)
  298. {
  299. float t = relative / diff;
  300. shapeInfo.finalWeight = std::min(t, 1.0f);
  301. }
  302. else
  303. shapeInfo.finalWeight = 0.0f;
  304. }
  305. }
  306. // Last frame
  307. {
  308. UINT32 lastFrame = channelInfo.shapeStart + channelInfo.shapeCount - 1;
  309. MorphShapeInfo& prevShapeInfo = anim->morphShapeInfos[lastFrame - 1];
  310. MorphShapeInfo& shapeInfo = anim->morphShapeInfos[lastFrame];
  311. float relative = frameWeight - shapeInfo.frameWeight;
  312. if (relative <= 0.0f)
  313. {
  314. float diff = shapeInfo.frameWeight - prevShapeInfo.frameWeight;
  315. if (diff > 0.0f)
  316. {
  317. float t = -relative / diff;
  318. shapeInfo.finalWeight = 1.0f - std::min(t, 1.0f);
  319. }
  320. else
  321. shapeInfo.finalWeight = 1.0f;
  322. }
  323. else // If past the final frame we clamp
  324. shapeInfo.finalWeight = 1.0f;
  325. }
  326. }
  327. for(UINT32 j = 0; j < channelInfo.shapeCount; j++)
  328. {
  329. MorphShapeInfo& shapeInfo = anim->morphShapeInfos[channelInfo.shapeStart + j];
  330. shapeInfo.finalWeight *= channelInfo.weight;
  331. }
  332. }
  333. // Generate morph shape vertices
  334. if(anim->morphChannelWeightsDirty || hasMorphCurves)
  335. {
  336. SPtr<MeshData> meshData = bs_shared_ptr_new<MeshData>(anim->numMorphVertices, 0, mBlendShapeVertexDesc);
  337. UINT8* bufferData = meshData->getData();
  338. memset(bufferData, 0, meshData->getSize());
  339. UINT32 tempDataSize = (sizeof(Vector3) + sizeof(float)) * anim->numMorphVertices;
  340. UINT8* tempData = (UINT8*)bs_stack_alloc(tempDataSize);
  341. memset(tempData, 0, tempDataSize);
  342. Vector3* tempNormals = (Vector3*)tempData;
  343. float* accumulatedWeight = (float*)(tempData + sizeof(Vector3) * anim->numMorphVertices);
  344. UINT8* positions = meshData->getElementData(VES_POSITION, 1, 1);
  345. UINT8* normals = meshData->getElementData(VES_NORMAL, 1, 1);
  346. UINT32 stride = mBlendShapeVertexDesc->getVertexStride(1);
  347. for(UINT32 i = 0; i < anim->numMorphShapes; i++)
  348. {
  349. const MorphShapeInfo& info = anim->morphShapeInfos[i];
  350. float absWeight = Math::abs(info.finalWeight);
  351. if (absWeight < 0.0001f)
  352. continue;
  353. const Vector<MorphVertex>& morphVertices = info.shape->getVertices();
  354. UINT32 numVertices = (UINT32)morphVertices.size();
  355. for(UINT32 j = 0; j < numVertices; j++)
  356. {
  357. const MorphVertex& vertex = morphVertices[j];
  358. Vector3* destPos = (Vector3*)(positions + vertex.sourceIdx * stride);
  359. *destPos += vertex.deltaPosition * info.finalWeight;
  360. tempNormals[vertex.sourceIdx] += vertex.deltaNormal * info.finalWeight;
  361. accumulatedWeight[vertex.sourceIdx] += absWeight;
  362. }
  363. }
  364. for(UINT32 i = 0; i < anim->numMorphVertices; i++)
  365. {
  366. PackedNormal* destNrm = (PackedNormal*)(normals + i * stride);
  367. if (accumulatedWeight[i] > 0.0001f)
  368. {
  369. Vector3 normal = tempNormals[i] / accumulatedWeight[i];
  370. normal /= 2.0f; // Accumulated normal is in range [-2, 2] but our normal packing method assumes [-1, 1] range
  371. MeshUtility::packNormals(&normal, (UINT8*)destNrm, 1, sizeof(Vector3), stride);
  372. destNrm->w = (UINT8)(std::min(1.0f, accumulatedWeight[i]) * 255.999f);
  373. }
  374. else
  375. {
  376. *destNrm = { 127, 127, 127, 0 };
  377. }
  378. }
  379. bs_stack_free(tempData);
  380. animInfo.morphShapeInfo.meshData = meshData;
  381. animInfo.morphShapeInfo.version++;
  382. anim->morphChannelWeightsDirty = false;
  383. }
  384. hasAnimInfo = true;
  385. }
  386. else
  387. animInfo.morphShapeInfo.version = 1;
  388. if (hasAnimInfo)
  389. renderData.infos[anim->id] = animInfo;
  390. }
  391. // Increments counter and ensures all writes are recorded
  392. mWorkerState.store(WorkerState::DataReady, std::memory_order_release);
  393. mDataReadyCount.fetch_add(1, std::memory_order_acq_rel);
  394. }
  395. void AnimationManager::waitUntilComplete()
  396. {
  397. mAnimationWorker->wait();
  398. // Read counter, and ensure all reads are done after writes on anim thread complete
  399. INT32 dataReadyCount = mDataReadyCount.load(std::memory_order_acquire);
  400. if (dataReadyCount > CoreThread::NUM_SYNC_BUFFERS)
  401. {
  402. LOGERR("Animation manager threading issue. Too many entries in queue: " + toString(dataReadyCount));
  403. assert(dataReadyCount <= CoreThread::NUM_SYNC_BUFFERS);
  404. }
  405. mDataReady = dataReadyCount > 0;
  406. if (!mDataReady)
  407. return;
  408. mDataReadyCount.fetch_sub(1, std::memory_order_release);
  409. mPoseReadBufferIdx = (mPoseReadBufferIdx + 1) % CoreThread::NUM_SYNC_BUFFERS;
  410. }
  411. const RendererAnimationData& AnimationManager::getRendererData()
  412. {
  413. if (!mDataReady)
  414. {
  415. static RendererAnimationData dummy;
  416. return dummy;
  417. }
  418. return mAnimData[mPoseReadBufferIdx];
  419. }
  420. UINT64 AnimationManager::registerAnimation(Animation* anim)
  421. {
  422. mAnimations[mNextId] = anim;
  423. return mNextId++;
  424. }
  425. void AnimationManager::unregisterAnimation(UINT64 animId)
  426. {
  427. mAnimations.erase(animId);
  428. }
  429. AnimationManager& gAnimation()
  430. {
  431. return AnimationManager::instance();
  432. }
  433. }