BsAnimation.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsAnimation.h"
  4. #include "BsAnimationManager.h"
  5. #include "BsAnimationClip.h"
  6. #include "BsAnimationUtility.h"
  7. #include "BsSceneObject.h"
  8. namespace BansheeEngine
  9. {
  10. AnimationClipInfo::AnimationClipInfo()
  11. : fadeDirection(0.0f), fadeTime(0.0f), fadeLength(0.0f), curveVersion(0), layerIdx((UINT32)-1), stateIdx((UINT32)-1)
  12. { }
  13. AnimationClipInfo::AnimationClipInfo(const HAnimationClip& clip)
  14. : fadeDirection(0.0f), fadeTime(0.0f), fadeLength(0.0f), clip(clip), curveVersion(0), layerIdx((UINT32)-1), stateIdx((UINT32)-1)
  15. { }
  16. Blend1DInfo::Blend1DInfo(UINT32 numClips)
  17. : clips(nullptr), numClips(numClips)
  18. {
  19. if (numClips > 0)
  20. clips = bs_newN<BlendClipInfo>(numClips);
  21. }
  22. Blend1DInfo::~Blend1DInfo()
  23. {
  24. if(clips != nullptr)
  25. bs_deleteN(clips, numClips);
  26. }
  27. AnimationProxy::AnimationProxy(UINT64 id)
  28. : id(id), layers(nullptr), numLayers(0), numSceneObjects(0), sceneObjectInfos(nullptr)
  29. , sceneObjectTransforms(nullptr), genericCurveOutputs(nullptr)
  30. { }
  31. AnimationProxy::~AnimationProxy()
  32. {
  33. clear();
  34. }
  35. void AnimationProxy::clear()
  36. {
  37. if (layers == nullptr)
  38. return;
  39. for(UINT32 i = 0; i < numLayers; i++)
  40. {
  41. AnimationStateLayer& layer = layers[i];
  42. for(UINT32 j = 0; j < layer.numStates; j++)
  43. {
  44. AnimationState& state = layer.states[j];
  45. if(state.curves != nullptr)
  46. {
  47. {
  48. UINT32 numCurves = (UINT32)state.curves->position.size();
  49. for (UINT32 k = 0; k < numCurves; k++)
  50. state.positionCaches[k].~TCurveCache();
  51. }
  52. {
  53. UINT32 numCurves = (UINT32)state.curves->rotation.size();
  54. for (UINT32 k = 0; k < numCurves; k++)
  55. state.rotationCaches[k].~TCurveCache();
  56. }
  57. {
  58. UINT32 numCurves = (UINT32)state.curves->scale.size();
  59. for (UINT32 k = 0; k < numCurves; k++)
  60. state.scaleCaches[k].~TCurveCache();
  61. }
  62. {
  63. UINT32 numCurves = (UINT32)state.curves->generic.size();
  64. for (UINT32 k = 0; k < numCurves; k++)
  65. state.genericCaches[k].~TCurveCache();
  66. }
  67. }
  68. if(skeleton != nullptr)
  69. {
  70. UINT32 numBones = skeleton->getNumBones();
  71. for (UINT32 k = 0; k < numBones; k++)
  72. state.boneToCurveMapping[k].~AnimationCurveMapping();
  73. }
  74. if(state.soToCurveMapping != nullptr)
  75. {
  76. for(UINT32 k = 0; k < numSceneObjects; k++)
  77. state.soToCurveMapping[k].~AnimationCurveMapping();
  78. }
  79. state.~AnimationState();
  80. }
  81. layer.~AnimationStateLayer();
  82. }
  83. // All of the memory is part of the same buffer, so we only need to free the first element
  84. bs_free(layers);
  85. layers = nullptr;
  86. genericCurveOutputs = nullptr;
  87. sceneObjectInfos = nullptr;
  88. sceneObjectTransforms = nullptr;
  89. numLayers = 0;
  90. numSceneObjects = 0;
  91. numGenericCurves = 0;
  92. }
  93. void AnimationProxy::rebuild(const SPtr<Skeleton>& skeleton, const SkeletonMask& mask,
  94. Vector<AnimationClipInfo>& clipInfos, const Vector<AnimatedSceneObject>& sceneObjects)
  95. {
  96. this->skeleton = skeleton;
  97. this->skeletonMask = skeletonMask;
  98. // Note: I could avoid having a separate allocation for LocalSkeletonPoses and use the same buffer as the rest
  99. // of AnimationProxy
  100. if (skeleton != nullptr)
  101. skeletonPose = LocalSkeletonPose(skeleton->getNumBones());
  102. numSceneObjects = (UINT32)sceneObjects.size();
  103. if (numSceneObjects > 0)
  104. sceneObjectPose = LocalSkeletonPose(numSceneObjects);
  105. else
  106. sceneObjectPose = LocalSkeletonPose();
  107. rebuild(clipInfos, sceneObjects);
  108. }
  109. void AnimationProxy::rebuild(Vector<AnimationClipInfo>& clipInfos, const Vector<AnimatedSceneObject>& sceneObjects)
  110. {
  111. clear();
  112. bs_frame_mark();
  113. {
  114. FrameVector<bool> clipLoadState(clipInfos.size());
  115. FrameVector<AnimationStateLayer> tempLayers;
  116. UINT32 clipIdx = 0;
  117. for (auto& clipInfo : clipInfos)
  118. {
  119. UINT32 layer = clipInfo.state.layer;
  120. if (layer == (UINT32)-1)
  121. layer = 0;
  122. else
  123. layer += 1;
  124. auto iterFind = std::find_if(tempLayers.begin(), tempLayers.end(),
  125. [&](auto& x)
  126. {
  127. return x.index == layer;
  128. });
  129. bool isLoaded = clipInfo.clip.isLoaded();
  130. clipLoadState[clipIdx] = isLoaded;
  131. if (iterFind == tempLayers.end())
  132. {
  133. tempLayers.push_back(AnimationStateLayer());
  134. AnimationStateLayer& newLayer = tempLayers.back();
  135. newLayer.index = layer;
  136. newLayer.additive = isLoaded && clipInfo.clip->isAdditive();
  137. }
  138. clipIdx++;
  139. }
  140. std::sort(tempLayers.begin(), tempLayers.end(),
  141. [&](auto& x, auto& y)
  142. {
  143. return x.index < y.index;
  144. });
  145. numLayers = (UINT32)tempLayers.size();
  146. UINT32 numClips = (UINT32)clipInfos.size();
  147. UINT32 numBones;
  148. if (skeleton != nullptr)
  149. numBones = skeleton->getNumBones();
  150. else
  151. numBones = 0;
  152. UINT32 numPosCurves = 0;
  153. UINT32 numRotCurves = 0;
  154. UINT32 numScaleCurves = 0;
  155. clipIdx = 0;
  156. for (auto& clipInfo : clipInfos)
  157. {
  158. bool isLoaded = clipLoadState[clipIdx++];
  159. if (!isLoaded)
  160. continue;
  161. SPtr<AnimationCurves> curves = clipInfo.clip->getCurves();
  162. numPosCurves += (UINT32)curves->position.size();
  163. numRotCurves += (UINT32)curves->rotation.size();
  164. numScaleCurves += (UINT32)curves->scale.size();
  165. }
  166. numGenericCurves = 0;
  167. if(clipInfos.size() > 0 && clipLoadState[0])
  168. {
  169. SPtr<AnimationCurves> curves = clipInfos[0].clip->getCurves();
  170. numGenericCurves = (UINT32)curves->generic.size();
  171. }
  172. UINT32* mappedBoneIndices = (UINT32*)bs_frame_alloc(sizeof(UINT32) * numSceneObjects);
  173. for (UINT32 i = 0; i < numSceneObjects; i++)
  174. mappedBoneIndices[i] = -1;
  175. UINT32 numBoneMappedSOs = 0;
  176. if (skeleton != nullptr)
  177. {
  178. for (UINT32 i = 0; i < numSceneObjects; i++)
  179. {
  180. if (sceneObjects[i].so.isDestroyed(true))
  181. continue;
  182. // Empty string always means root bone
  183. if (sceneObjects[i].curveName.empty())
  184. {
  185. UINT32 rootBoneIdx = skeleton->getRootBoneIndex();
  186. if (rootBoneIdx != (UINT32)-1)
  187. {
  188. mappedBoneIndices[i] = rootBoneIdx;
  189. numBoneMappedSOs++;
  190. }
  191. }
  192. else
  193. {
  194. for (UINT32 j = 0; j < numBones; j++)
  195. {
  196. if (skeleton->getBoneInfo(j).name == sceneObjects[i].curveName)
  197. {
  198. mappedBoneIndices[i] = j;
  199. numBoneMappedSOs++;
  200. break;
  201. }
  202. }
  203. }
  204. }
  205. }
  206. UINT32 numBoneMappings = numBones * numClips;
  207. UINT32 layersSize = sizeof(AnimationStateLayer) * numLayers;
  208. UINT32 clipsSize = sizeof(AnimationState) * numClips;
  209. UINT32 boneMappingSize = numBoneMappings * sizeof(AnimationCurveMapping);
  210. UINT32 posCacheSize = numPosCurves * sizeof(TCurveCache<Vector3>);
  211. UINT32 rotCacheSize = numRotCurves * sizeof(TCurveCache<Quaternion>);
  212. UINT32 scaleCacheSize = numScaleCurves * sizeof(TCurveCache<Vector3>);
  213. UINT32 genCacheSize = numGenericCurves * sizeof(TCurveCache<float>);
  214. UINT32 genericCurveOutputSize = numGenericCurves * sizeof(float);
  215. UINT32 sceneObjectIdsSize = numSceneObjects * sizeof(AnimatedSceneObjectInfo);
  216. UINT32 sceneObjectTransformsSize = numBoneMappedSOs * sizeof(Matrix4);
  217. UINT8* data = (UINT8*)bs_alloc(layersSize + clipsSize + boneMappingSize + posCacheSize + rotCacheSize +
  218. scaleCacheSize + genCacheSize + genericCurveOutputSize + sceneObjectIdsSize + sceneObjectTransformsSize);
  219. layers = (AnimationStateLayer*)data;
  220. memcpy(layers, tempLayers.data(), layersSize);
  221. data += layersSize;
  222. AnimationState* states = (AnimationState*)data;
  223. for(UINT32 i = 0; i < numClips; i++)
  224. new (&states[i]) AnimationState();
  225. data += clipsSize;
  226. AnimationCurveMapping* boneMappings = (AnimationCurveMapping*)data;
  227. for (UINT32 i = 0; i < numBoneMappings; i++)
  228. new (&boneMappings[i]) AnimationCurveMapping();
  229. data += boneMappingSize;
  230. TCurveCache<Vector3>* posCache = (TCurveCache<Vector3>*)data;
  231. for (UINT32 i = 0; i < numPosCurves; i++)
  232. new (&posCache[i]) TCurveCache<Vector3>();
  233. data += posCacheSize;
  234. TCurveCache<Quaternion>* rotCache = (TCurveCache<Quaternion>*)data;
  235. for (UINT32 i = 0; i < numRotCurves; i++)
  236. new (&rotCache[i]) TCurveCache<Quaternion>();
  237. data += rotCacheSize;
  238. TCurveCache<Vector3>* scaleCache = (TCurveCache<Vector3>*)data;
  239. for (UINT32 i = 0; i < numScaleCurves; i++)
  240. new (&scaleCache[i]) TCurveCache<Vector3>();
  241. data += scaleCacheSize;
  242. TCurveCache<float>* genCache = (TCurveCache<float>*)data;
  243. for (UINT32 i = 0; i < numGenericCurves; i++)
  244. new (&genCache[i]) TCurveCache<float>();
  245. data += genCacheSize;
  246. genericCurveOutputs = (float*)data;
  247. data += genericCurveOutputSize;
  248. sceneObjectInfos = (AnimatedSceneObjectInfo*)data;
  249. data += sceneObjectIdsSize;
  250. sceneObjectTransforms = (Matrix4*)data;
  251. for (UINT32 i = 0; i < numBoneMappedSOs; i++)
  252. sceneObjectTransforms[i] = Matrix4::IDENTITY;
  253. data += sceneObjectTransformsSize;
  254. UINT32 curLayerIdx = 0;
  255. UINT32 curStateIdx = 0;
  256. // Note: Hidden dependency. First clip info must be in layers[0].states[0] (needed for generic curves which only
  257. // use the primary clip).
  258. for(UINT32 i = 0; i < numLayers; i++)
  259. {
  260. AnimationStateLayer& layer = layers[i];
  261. layer.states = &states[curStateIdx];
  262. layer.numStates = 0;
  263. UINT32 localStateIdx = 0;
  264. for(UINT32 j = 0; j < (UINT32)clipInfos.size(); j++)
  265. {
  266. AnimationClipInfo& clipInfo = clipInfos[j];
  267. UINT32 clipLayer = clipInfo.state.layer;
  268. if (clipLayer == (UINT32)-1)
  269. clipLayer = 0;
  270. else
  271. clipLayer += 1;
  272. if (clipLayer != layer.index)
  273. continue;
  274. AnimationState& state = states[curStateIdx];
  275. state.loop = clipInfo.state.wrapMode == AnimWrapMode::Loop;
  276. state.time = clipInfo.state.time;
  277. // Calculate weight if fading is active
  278. float weight = clipInfo.state.weight;
  279. //// Assumes time is clamped to [0, fadeLength] and fadeLength != 0
  280. if(clipInfo.fadeDirection < 0.0f)
  281. {
  282. float t = clipInfo.fadeTime / clipInfo.fadeLength;
  283. weight *= (1.0f - t);
  284. }
  285. else if(clipInfo.fadeDirection > 0.0f)
  286. {
  287. float t = clipInfo.fadeTime / clipInfo.fadeLength;
  288. weight *= t;
  289. }
  290. state.weight = weight;
  291. // Set up individual curves and their caches
  292. bool isClipValid = clipLoadState[j];
  293. if (isClipValid)
  294. {
  295. state.curves = clipInfo.clip->getCurves();
  296. state.disabled = false;
  297. }
  298. else
  299. {
  300. static SPtr<AnimationCurves> zeroCurves = bs_shared_ptr_new<AnimationCurves>();
  301. state.curves = zeroCurves;
  302. state.disabled = true;
  303. }
  304. state.positionCaches = posCache;
  305. posCache += state.curves->position.size();
  306. state.rotationCaches = rotCache;
  307. rotCache += state.curves->rotation.size();
  308. state.scaleCaches = scaleCache;
  309. scaleCache += state.curves->scale.size();
  310. state.genericCaches = genCache;
  311. genCache += state.curves->generic.size();
  312. clipInfo.layerIdx = curLayerIdx;
  313. clipInfo.stateIdx = localStateIdx;
  314. if(isClipValid)
  315. clipInfo.curveVersion = clipInfo.clip->getVersion();
  316. // Set up bone mapping
  317. if (skeleton != nullptr)
  318. {
  319. state.boneToCurveMapping = &boneMappings[curStateIdx * numBones];
  320. if (isClipValid)
  321. {
  322. clipInfo.clip->getBoneMapping(*skeleton, state.boneToCurveMapping);
  323. }
  324. else
  325. {
  326. AnimationCurveMapping emptyMapping = { (UINT32)-1, (UINT32)-1, (UINT32)-1 };
  327. for (UINT32 i = 0; i < numBones; i++)
  328. state.boneToCurveMapping[i] = emptyMapping;
  329. }
  330. }
  331. else
  332. state.boneToCurveMapping = nullptr;
  333. layer.numStates++;
  334. curStateIdx++;
  335. localStateIdx++;
  336. }
  337. curLayerIdx++;
  338. // Must be larger than zero otherwise the layer.states pointer will point to data held by some other layer
  339. assert(layer.numStates > 0);
  340. }
  341. UINT32 boneIdx = 0;
  342. for(UINT32 i = 0; i < numSceneObjects; i++)
  343. {
  344. HSceneObject so = sceneObjects[i].so;
  345. AnimatedSceneObjectInfo& soInfo = sceneObjectInfos[i];
  346. soInfo.id = so.getInstanceId();
  347. soInfo.boneIdx = mappedBoneIndices[i];
  348. bool isSOValid = !so.isDestroyed(true);
  349. if (isSOValid)
  350. soInfo.hash = so->getTransformHash();
  351. else
  352. soInfo.hash = 0;
  353. // If no bone mapping, find curves directly
  354. if(soInfo.boneIdx == -1)
  355. {
  356. soInfo.curveIndices = { (UINT32)-1, (UINT32)-1, (UINT32)-1 };
  357. if (isSOValid)
  358. {
  359. for (UINT32 j = 0; j < (UINT32)clipInfos.size(); j++)
  360. {
  361. AnimationClipInfo& clipInfo = clipInfos[j];
  362. soInfo.layerIdx = clipInfo.layerIdx;
  363. soInfo.stateIdx = clipInfo.stateIdx;
  364. bool isClipValid = clipLoadState[j];
  365. if (isClipValid)
  366. {
  367. // Note: If there are multiple clips with the relevant curve name, we only use the first
  368. clipInfo.clip->getCurveMapping(sceneObjects[i].curveName, soInfo.curveIndices);
  369. break;
  370. }
  371. }
  372. }
  373. }
  374. else
  375. {
  376. // No need to check if SO is valid, if it has a bone connection it must be
  377. sceneObjectTransforms[boneIdx] = so->getWorldTfrm();
  378. boneIdx++;
  379. }
  380. }
  381. bs_frame_free(mappedBoneIndices);
  382. }
  383. bs_frame_clear();
  384. }
  385. void AnimationProxy::updateValues(const Vector<AnimationClipInfo>& clipInfos)
  386. {
  387. for(auto& clipInfo : clipInfos)
  388. {
  389. AnimationState& state = layers[clipInfo.layerIdx].states[clipInfo.stateIdx];
  390. state.loop = clipInfo.state.wrapMode == AnimWrapMode::Loop;
  391. state.weight = clipInfo.state.weight;
  392. state.time = clipInfo.state.time;
  393. }
  394. }
  395. void AnimationProxy::updateTransforms(const Vector<AnimatedSceneObject>& sceneObjects)
  396. {
  397. UINT32 boneIdx = 0;
  398. for (UINT32 i = 0; i < numSceneObjects; i++)
  399. {
  400. HSceneObject so = sceneObjects[i].so;
  401. if (so.isDestroyed(true))
  402. {
  403. sceneObjectInfos[i].hash = 0;
  404. continue;
  405. }
  406. sceneObjectInfos[i].hash = so->getTransformHash();
  407. if (sceneObjectInfos[i].boneIdx == -1)
  408. continue;
  409. sceneObjectTransforms[boneIdx] = sceneObjects[i].so->getWorldTfrm();
  410. boneIdx++;
  411. }
  412. }
  413. void AnimationProxy::updateTime(const Vector<AnimationClipInfo>& clipInfos)
  414. {
  415. for (auto& clipInfo : clipInfos)
  416. {
  417. AnimationState& state = layers[clipInfo.layerIdx].states[clipInfo.stateIdx];
  418. state.time = clipInfo.state.time;
  419. }
  420. }
  421. Animation::Animation()
  422. : mDefaultWrapMode(AnimWrapMode::Loop), mDefaultSpeed(1.0f), mDirty(AnimDirtyStateFlag::Skeleton)
  423. , mGenericCurveValuesValid(false)
  424. {
  425. mId = AnimationManager::instance().registerAnimation(this);
  426. mAnimProxy = bs_shared_ptr_new<AnimationProxy>(mId);
  427. }
  428. Animation::~Animation()
  429. {
  430. AnimationManager::instance().unregisterAnimation(mId);
  431. }
  432. void Animation::setSkeleton(const SPtr<Skeleton>& skeleton)
  433. {
  434. mSkeleton = skeleton;
  435. mDirty |= AnimDirtyStateFlag::Skeleton;
  436. }
  437. void Animation::setMask(const SkeletonMask& mask)
  438. {
  439. mSkeletonMask = mask;
  440. mDirty |= AnimDirtyStateFlag::Skeleton;
  441. }
  442. void Animation::setWrapMode(AnimWrapMode wrapMode)
  443. {
  444. mDefaultWrapMode = wrapMode;
  445. for (auto& clipInfo : mClipInfos)
  446. clipInfo.state.wrapMode = wrapMode;
  447. mDirty |= AnimDirtyStateFlag::Value;
  448. }
  449. void Animation::setSpeed(float speed)
  450. {
  451. mDefaultSpeed = speed;
  452. for (auto& clipInfo : mClipInfos)
  453. {
  454. // Special case: Ignore non-moving ones
  455. if(!clipInfo.state.stopped)
  456. clipInfo.state.speed = speed;
  457. }
  458. mDirty |= AnimDirtyStateFlag::Value;
  459. }
  460. void Animation::play(const HAnimationClip& clip)
  461. {
  462. AnimationClipInfo* clipInfo = addClip(clip, (UINT32)-1);
  463. if(clipInfo != nullptr)
  464. {
  465. clipInfo->state.time = 0.0f;
  466. clipInfo->state.speed = mDefaultSpeed;
  467. clipInfo->state.weight = 1.0f;
  468. clipInfo->state.wrapMode = mDefaultWrapMode;
  469. }
  470. mDirty |= AnimDirtyStateFlag::Value;
  471. }
  472. void Animation::blendAdditive(const HAnimationClip& clip, float weight, float fadeLength, UINT32 layer)
  473. {
  474. if(clip != nullptr && !clip->isAdditive())
  475. {
  476. LOGWRN("blendAdditive() called with a clip that doesn't contain additive animation. Ignoring.");
  477. // Stop any clips on this layer, even if invalid
  478. HAnimationClip nullClip;
  479. addClip(nullClip, layer);
  480. return;
  481. }
  482. AnimationClipInfo* clipInfo = addClip(clip, layer);
  483. if (clipInfo != nullptr)
  484. {
  485. clipInfo->state.time = 0.0f;
  486. clipInfo->state.speed = mDefaultSpeed;
  487. clipInfo->state.weight = weight;
  488. clipInfo->state.wrapMode = mDefaultWrapMode;
  489. if(fadeLength > 0.0f)
  490. {
  491. clipInfo->fadeDirection = 1.0f;
  492. clipInfo->fadeTime = 0.0f;
  493. clipInfo->fadeLength = fadeLength;
  494. }
  495. mDirty |= AnimDirtyStateFlag::Value;
  496. }
  497. }
  498. void Animation::blend1D(const Blend1DInfo& info, float t)
  499. {
  500. if (info.numClips == 0)
  501. return;
  502. // Find valid range
  503. float startPos = 0.0f;
  504. float endPos = 0.0f;
  505. for (UINT32 i = 0; i < info.numClips; i++)
  506. {
  507. startPos = std::min(startPos, info.clips[i].position);
  508. endPos = std::min(endPos, info.clips[i].position);
  509. }
  510. float length = endPos - startPos;
  511. if(Math::approxEquals(length, 0.0f) || info.numClips < 2)
  512. {
  513. play(info.clips[0].clip);
  514. return;
  515. }
  516. // Clamp or loop time
  517. bool loop = mDefaultWrapMode == AnimWrapMode::Loop;
  518. if (t < startPos)
  519. {
  520. if (loop)
  521. t = t - std::floor(t / length) * length;
  522. else // Clamping
  523. t = startPos;
  524. }
  525. if (t > endPos)
  526. {
  527. if (loop)
  528. t = t - std::floor(t / length) * length;
  529. else // Clamping
  530. t = endPos;
  531. }
  532. // Find keys to blend between
  533. UINT32 leftKey = 0;
  534. UINT32 rightKey = 0;
  535. INT32 start = 0;
  536. INT32 searchLength = (INT32)info.numClips;
  537. while (searchLength > 0)
  538. {
  539. INT32 half = searchLength >> 1;
  540. INT32 mid = start + half;
  541. if (t < info.clips[mid].position)
  542. {
  543. searchLength = half;
  544. }
  545. else
  546. {
  547. start = mid + 1;
  548. searchLength -= (half + 1);
  549. }
  550. }
  551. leftKey = std::max(0, start - 1);
  552. rightKey = std::min(start, (INT32)info.numClips - 1);
  553. float interpLength = info.clips[rightKey].position - info.clips[leftKey].position;
  554. t = (t - info.clips[leftKey].position) / interpLength;
  555. // Add clips and set weights
  556. for(UINT32 i = 0; i < info.numClips; i++)
  557. {
  558. AnimationClipInfo* clipInfo = addClip(info.clips[i].clip, (UINT32)-1, i == 0);
  559. if (clipInfo != nullptr)
  560. {
  561. clipInfo->state.time = 0.0f;
  562. clipInfo->state.stopped = true;
  563. clipInfo->state.speed = 0.0f;
  564. clipInfo->state.wrapMode = AnimWrapMode::Clamp;
  565. if (i == leftKey)
  566. clipInfo->state.weight = 1.0f - t;
  567. else if (i == rightKey)
  568. clipInfo->state.weight = t;
  569. else
  570. clipInfo->state.weight = 0.0f;
  571. }
  572. }
  573. mDirty |= AnimDirtyStateFlag::Value;
  574. }
  575. void Animation::blend2D(const Blend2DInfo& info, const Vector2& t)
  576. {
  577. AnimationClipInfo* topLeftClipInfo = addClip(info.topLeftClip, (UINT32)-1, true);
  578. if (topLeftClipInfo != nullptr)
  579. {
  580. topLeftClipInfo->state.time = 0.0f;
  581. topLeftClipInfo->state.stopped = true;
  582. topLeftClipInfo->state.speed = 0.0f;
  583. topLeftClipInfo->state.weight = (1.0f - t.x) * (1.0f - t.y);
  584. topLeftClipInfo->state.wrapMode = AnimWrapMode::Clamp;
  585. }
  586. AnimationClipInfo* topRightClipInfo = addClip(info.topRightClip, (UINT32)-1, false);
  587. if (topRightClipInfo != nullptr)
  588. {
  589. topRightClipInfo->state.time = 0.0f;
  590. topRightClipInfo->state.stopped = true;
  591. topLeftClipInfo->state.speed = 0.0f;
  592. topRightClipInfo->state.weight = t.x * (1.0f - t.y);
  593. topRightClipInfo->state.wrapMode = AnimWrapMode::Clamp;
  594. }
  595. AnimationClipInfo* botLeftClipInfo = addClip(info.botLeftClip, (UINT32)-1, false);
  596. if (botLeftClipInfo != nullptr)
  597. {
  598. botLeftClipInfo->state.time = 0.0f;
  599. botLeftClipInfo->state.stopped = true;
  600. topLeftClipInfo->state.speed = 0.0f;
  601. botLeftClipInfo->state.weight = (1.0f - t.x) * t.y;
  602. botLeftClipInfo->state.wrapMode = AnimWrapMode::Clamp;
  603. }
  604. AnimationClipInfo* botRightClipInfo = addClip(info.botRightClip, (UINT32)-1, false);
  605. if (botRightClipInfo != nullptr)
  606. {
  607. botRightClipInfo->state.time = 0.0f;
  608. botRightClipInfo->state.stopped = true;
  609. botRightClipInfo->state.speed = 0.0f;
  610. botRightClipInfo->state.weight = t.x * t.y;
  611. botRightClipInfo->state.wrapMode = AnimWrapMode::Clamp;
  612. }
  613. mDirty |= AnimDirtyStateFlag::Value;
  614. }
  615. void Animation::crossFade(const HAnimationClip& clip, float fadeLength)
  616. {
  617. bool isFading = fadeLength > 0.0f;
  618. if(!isFading)
  619. {
  620. play(clip);
  621. return;
  622. }
  623. AnimationClipInfo* clipInfo = addClip(clip, (UINT32)-1, false);
  624. if (clipInfo != nullptr)
  625. {
  626. clipInfo->state.time = 0.0f;
  627. clipInfo->state.speed = mDefaultSpeed;
  628. clipInfo->state.weight = 1.0f;
  629. clipInfo->state.wrapMode = mDefaultWrapMode;
  630. // Set up fade lengths
  631. clipInfo->fadeDirection = 1.0f;
  632. clipInfo->fadeTime = 0.0f;
  633. clipInfo->fadeLength = fadeLength;
  634. for (auto& entry : mClipInfos)
  635. {
  636. if (entry.state.layer == (UINT32)-1 && entry.clip != clip)
  637. {
  638. // If other clips are already cross-fading, we need to persist their current weight before starting
  639. // a new crossfade. We do that by adjusting the fade times.
  640. if(clipInfo->fadeDirection != 0 && clipInfo->fadeTime < clipInfo->fadeLength)
  641. {
  642. float t = clipInfo->fadeTime / clipInfo->fadeLength;
  643. if (clipInfo->fadeDirection < 0.0f)
  644. t = (1.0f - t);
  645. clipInfo->state.weight *= t;
  646. }
  647. clipInfo->fadeDirection = -1.0f;
  648. clipInfo->fadeTime = 0.0f;
  649. clipInfo->fadeLength = fadeLength;
  650. }
  651. }
  652. }
  653. mDirty |= AnimDirtyStateFlag::Value;
  654. }
  655. void Animation::stop(UINT32 layer)
  656. {
  657. bs_frame_mark();
  658. {
  659. FrameVector<AnimationClipInfo> newClips;
  660. for (auto& clipInfo : mClipInfos)
  661. {
  662. if (clipInfo.state.layer != layer)
  663. newClips.push_back(clipInfo);
  664. else
  665. mDirty |= AnimDirtyStateFlag::Layout;
  666. }
  667. mClipInfos.resize(newClips.size());
  668. memcpy(mClipInfos.data(), newClips.data(), sizeof(AnimationClipInfo) * newClips.size());
  669. }
  670. bs_frame_clear();
  671. }
  672. void Animation::stopAll()
  673. {
  674. mClipInfos.clear();
  675. mDirty |= AnimDirtyStateFlag::Layout;
  676. }
  677. AnimationClipInfo* Animation::addClip(const HAnimationClip& clip, UINT32 layer, bool stopExisting)
  678. {
  679. AnimationClipInfo* output = nullptr;
  680. bool hasExisting = false;
  681. // Search for existing
  682. for (auto& clipInfo : mClipInfos)
  683. {
  684. if (clipInfo.state.layer == layer)
  685. {
  686. if (clipInfo.clip == clip)
  687. output = &clipInfo;
  688. else if (stopExisting)
  689. hasExisting = true;
  690. }
  691. }
  692. // Doesn't exist or found extra animations, rebuild
  693. if (output == nullptr || hasExisting)
  694. {
  695. bs_frame_mark();
  696. {
  697. FrameVector<AnimationClipInfo> newClips;
  698. for (auto& clipInfo : mClipInfos)
  699. {
  700. if (!stopExisting || clipInfo.state.layer != layer || clipInfo.clip == clip)
  701. newClips.push_back(clipInfo);
  702. }
  703. if (output == nullptr && clip != nullptr)
  704. newClips.push_back(AnimationClipInfo());
  705. mClipInfos.resize(newClips.size());
  706. memcpy(mClipInfos.data(), newClips.data(), sizeof(AnimationClipInfo) * newClips.size());
  707. mDirty |= AnimDirtyStateFlag::Layout;
  708. }
  709. bs_frame_clear();
  710. }
  711. // If new clip was added, get its address
  712. if (output == nullptr && clip != nullptr)
  713. {
  714. AnimationClipInfo& newInfo = mClipInfos.back();
  715. newInfo.clip = clip;
  716. newInfo.layerIdx = layer;
  717. output = &newInfo;
  718. }
  719. return output;
  720. }
  721. bool Animation::isPlaying() const
  722. {
  723. for(auto& clipInfo : mClipInfos)
  724. {
  725. if (clipInfo.clip.isLoaded())
  726. return true;
  727. }
  728. return false;
  729. }
  730. bool Animation::getState(const HAnimationClip& clip, AnimationClipState& state)
  731. {
  732. if (clip == nullptr)
  733. return false;
  734. for (auto& clipInfo : mClipInfos)
  735. {
  736. if (clipInfo.clip == clip)
  737. {
  738. state = clipInfo.state;
  739. return true;
  740. }
  741. }
  742. return false;
  743. }
  744. void Animation::setState(const HAnimationClip& clip, AnimationClipState state)
  745. {
  746. AnimationClipInfo* clipInfo = addClip(clip, state.layer, false);
  747. if (clipInfo == nullptr)
  748. return;
  749. clipInfo->state = state;
  750. mDirty |= AnimDirtyStateFlag::Value;
  751. }
  752. UINT32 Animation::getNumClips() const
  753. {
  754. return (UINT32)mClipInfos.size();
  755. }
  756. HAnimationClip Animation::getClip(UINT32 idx) const
  757. {
  758. if (idx >= (UINT32)mClipInfos.size())
  759. return HAnimationClip();
  760. return mClipInfos[idx].clip;
  761. }
  762. void Animation::triggerEvents(float lastFrameTime, float delta)
  763. {
  764. for (auto& clipInfo : mClipInfos)
  765. {
  766. if (!clipInfo.clip.isLoaded())
  767. continue;
  768. const Vector<AnimationEvent>& events = clipInfo.clip->getEvents();
  769. bool loop = clipInfo.state.wrapMode == AnimWrapMode::Loop;
  770. float start = lastFrameTime;
  771. float end = start + delta;
  772. float clipLength = clipInfo.clip->getLength();
  773. AnimationUtility::wrapTime(start, 0.0f, clipLength, loop);
  774. AnimationUtility::wrapTime(end, 0.0f, clipLength, false);
  775. for (auto& event : events)
  776. {
  777. if (event.time > start && event.time <= end)
  778. onEventTriggered(clipInfo.clip, event.name);
  779. }
  780. // Check the looped portion
  781. if(loop && end >= clipLength)
  782. {
  783. start = 0.0f;
  784. end = end - clipLength;
  785. for (auto& event : events)
  786. {
  787. if (event.time > start && event.time <= end)
  788. onEventTriggered(clipInfo.clip, event.name);
  789. }
  790. }
  791. }
  792. }
  793. void Animation::mapCurveToSceneObject(const String& curve, const HSceneObject& so)
  794. {
  795. AnimatedSceneObject animSo = { so, curve };
  796. mSceneObjects[so.getInstanceId()] = animSo;
  797. mDirty |= AnimDirtyStateFlag::Skeleton;
  798. }
  799. void Animation::unmapSceneObject(const HSceneObject& so)
  800. {
  801. mSceneObjects.erase(so.getInstanceId());
  802. mDirty |= AnimDirtyStateFlag::Skeleton;
  803. }
  804. bool Animation::getGenericCurveValue(UINT32 curveIdx, float& value)
  805. {
  806. if (!mGenericCurveValuesValid || curveIdx >= (UINT32)mGenericCurveOutputs.size())
  807. return false;
  808. value = mGenericCurveOutputs[curveIdx];
  809. return true;
  810. }
  811. SPtr<Animation> Animation::create()
  812. {
  813. Animation* anim = new (bs_alloc<Animation>()) Animation();
  814. SPtr<Animation> animPtr = bs_core_ptr(anim);
  815. animPtr->_setThisPtr(animPtr);
  816. animPtr->initialize();
  817. return animPtr;
  818. }
  819. void Animation::updateAnimProxy(float timeDelta)
  820. {
  821. // Check if any of the clip curves are dirty and advance time, perform fading
  822. for (auto& clipInfo : mClipInfos)
  823. {
  824. float scaledTimeDelta = timeDelta * clipInfo.state.speed;
  825. clipInfo.state.time += scaledTimeDelta;
  826. if (clipInfo.clip.isLoaded() && clipInfo.curveVersion != clipInfo.clip->getVersion())
  827. mDirty |= AnimDirtyStateFlag::Layout;
  828. float fadeTime = clipInfo.fadeTime + scaledTimeDelta;
  829. clipInfo.fadeTime = Math::clamp(fadeTime, 0.0f, clipInfo.fadeLength);
  830. }
  831. if((UINT32)mDirty == 0) // Clean
  832. {
  833. mAnimProxy->updateTime(mClipInfos);
  834. }
  835. else
  836. {
  837. auto getAnimatedSOList = [&]()
  838. {
  839. Vector<AnimatedSceneObject> animatedSO(mSceneObjects.size());
  840. UINT32 idx = 0;
  841. for (auto& entry : mSceneObjects)
  842. animatedSO[idx++] = entry.second;
  843. return animatedSO;
  844. };
  845. bool didFullRebuild = false;
  846. if (mDirty.isSet(AnimDirtyStateFlag::Skeleton))
  847. {
  848. Vector<AnimatedSceneObject> animatedSOs = getAnimatedSOList();
  849. mAnimProxy->rebuild(mSkeleton, mSkeletonMask, mClipInfos, animatedSOs);
  850. didFullRebuild = true;
  851. }
  852. else if (mDirty.isSet(AnimDirtyStateFlag::Layout))
  853. {
  854. Vector<AnimatedSceneObject> animatedSOs = getAnimatedSOList();
  855. mAnimProxy->rebuild(mClipInfos, animatedSOs);
  856. didFullRebuild = true;
  857. }
  858. else if (mDirty.isSet(AnimDirtyStateFlag::Value))
  859. mAnimProxy->updateValues(mClipInfos);
  860. // Check if there are dirty transforms
  861. if(!didFullRebuild)
  862. {
  863. UINT32 numSceneObjects = (UINT32)mSceneObjects.size();
  864. for (UINT32 i = 0; i < numSceneObjects; i++)
  865. {
  866. UINT32 hash;
  867. HSceneObject so = mSceneObjects[i].so;
  868. if (so.isDestroyed(true))
  869. hash = 0;
  870. else
  871. hash = so->getTransformHash();
  872. if(hash != mAnimProxy->sceneObjectInfos[i].hash)
  873. {
  874. Vector<AnimatedSceneObject> animatedSOs = getAnimatedSOList();
  875. mAnimProxy->updateTransforms(animatedSOs);
  876. break;
  877. }
  878. }
  879. }
  880. }
  881. mDirty = AnimDirtyState();
  882. }
  883. void Animation::updateFromProxy()
  884. {
  885. // Write TRS animation results to relevant SceneObjects
  886. for(UINT32 i = 0; i < mAnimProxy->numSceneObjects; i++)
  887. {
  888. AnimatedSceneObjectInfo& soInfo = mAnimProxy->sceneObjectInfos[i];
  889. auto iterFind = mSceneObjects.find(soInfo.id);
  890. if (iterFind == mSceneObjects.end())
  891. continue;
  892. HSceneObject so = iterFind->second.so;
  893. if (so.isDestroyed(true))
  894. continue;
  895. if(soInfo.boneIdx != -1)
  896. {
  897. so->setPosition(mAnimProxy->skeletonPose.positions[soInfo.boneIdx]);
  898. so->setRotation(mAnimProxy->skeletonPose.rotations[soInfo.boneIdx]);
  899. so->setScale(mAnimProxy->skeletonPose.scales[soInfo.boneIdx]);
  900. }
  901. else
  902. {
  903. so->setPosition(mAnimProxy->sceneObjectPose.positions[i]);
  904. so->setRotation(mAnimProxy->sceneObjectPose.rotations[i]);
  905. so->setScale(mAnimProxy->sceneObjectPose.scales[i]);
  906. }
  907. soInfo.hash = so->getTransformHash();
  908. }
  909. // Must ensure that clip in the proxy and current primary clip are the same
  910. mGenericCurveValuesValid = false;
  911. if(mAnimProxy->numLayers > 0 && mAnimProxy->layers[0].numStates > 0)
  912. {
  913. const AnimationState& state = mAnimProxy->layers[0].states[0];
  914. if(!state.disabled && mClipInfos.size() > 0)
  915. {
  916. const AnimationClipInfo& clipInfo = mClipInfos[0];
  917. if (clipInfo.stateIdx == 0 && clipInfo.layerIdx == 0)
  918. {
  919. if (clipInfo.clip.isLoaded() && clipInfo.curveVersion == clipInfo.clip->getVersion())
  920. {
  921. UINT32 numGenericCurves = (UINT32)clipInfo.clip->getCurves()->generic.size();
  922. mGenericCurveValuesValid = numGenericCurves == mAnimProxy->numGenericCurves;
  923. }
  924. }
  925. }
  926. }
  927. if(mGenericCurveValuesValid)
  928. {
  929. mGenericCurveOutputs.resize(mAnimProxy->numGenericCurves);
  930. memcpy(mGenericCurveOutputs.data(), mAnimProxy->genericCurveOutputs, mAnimProxy->numGenericCurves * sizeof(float));
  931. }
  932. }
  933. }