AnimationCurve.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. //
  2. // AnimationCurve.cpp
  3. // cocos2d_libs
  4. //
  5. // Created by 徐俊杰 on 2020/5/15.
  6. //
  7. #include "rparticle/Math/AnimationCurve.h"
  8. using namespace std;
  9. #define kOneThird (1.0F / 3.0F)
  10. #define kMaxTan 5729577.9485111479F
  11. NS_RRP_BEGIN
  12. int ToInternalInfinity (int pre);
  13. int FromInternalInfinity (int pre);
  14. int ToInternalInfinity (int pre)
  15. {
  16. if (pre == kRepeat)
  17. return AnimationCurve::kInternalRepeat;
  18. else if (pre == kPingPong)
  19. return AnimationCurve::kInternalPingPong;
  20. else
  21. return AnimationCurve::kInternalClamp;
  22. }
  23. int FromInternalInfinity (int pre)
  24. {
  25. if (pre == AnimationCurve::kInternalRepeat)
  26. return kRepeat;
  27. else if (pre == AnimationCurve::kInternalPingPong)
  28. return kPingPong;
  29. else
  30. return kClampForever;
  31. }
  32. template<class T>
  33. KeyframeTpl<T>::KeyframeTpl (float t, const T& v)
  34. {
  35. time = t;
  36. value = v;
  37. inSlope = Zero<T>();
  38. outSlope = Zero<T>();
  39. #if UNITY_EDITOR
  40. tangentMode = 0;
  41. #endif
  42. }
  43. template<class T>
  44. void AnimationCurveTpl<T>::InvalidateCache ()
  45. {
  46. m_Cache.time = std::numeric_limits<float>::infinity ();
  47. m_Cache.index = 0;
  48. m_ClampCache.time = std::numeric_limits<float>::infinity ();
  49. m_ClampCache.index = 0;
  50. }
  51. template<class T>
  52. pair<float, float> AnimationCurveTpl<T>::GetRange () const
  53. {
  54. if (!m_Curve.empty ())
  55. return make_pair (m_Curve[0].time, m_Curve.back ().time);
  56. else
  57. return make_pair (std::numeric_limits<float>::infinity (), -std::numeric_limits<float>::infinity ());
  58. }
  59. ///@TODO: Handle step curves correctly
  60. template<class T>
  61. void AnimationCurveTpl<T>::EvaluateWithoutCache (float curveT, T& output)const
  62. {
  63. DebugAssertIf (!IsValid ());
  64. curveT = WrapTime (curveT);
  65. int lhsIndex, rhsIndex;
  66. FindIndexForSampling (m_Cache, curveT, lhsIndex, rhsIndex);
  67. const Keyframe& lhs = m_Curve[lhsIndex];
  68. const Keyframe& rhs = m_Curve[rhsIndex];
  69. float dx = rhs.time - lhs.time;
  70. T m1;
  71. T m2;
  72. float t;
  73. if (dx != 0.0F)
  74. {
  75. t = (curveT - lhs.time) / dx;
  76. m1 = lhs.outSlope * dx;
  77. m2 = rhs.inSlope * dx;
  78. }
  79. else
  80. {
  81. t = 0.0F;
  82. m1 = Zero<T>();
  83. m2 = Zero<T>();
  84. }
  85. output = HermiteInterpolate (t, lhs.value, m1, m2, rhs.value);
  86. HandleSteppedCurve(lhs, rhs, output);
  87. //TODO: IsFinite
  88. // DebugAssertIf(!IsFinite(output));
  89. }
  90. template<class T>
  91. inline void EvaluateCache (const typename AnimationCurveTpl<T>::Cache& cache, float curveT, T& output)
  92. {
  93. // DebugAssertIf (curveT < cache.time - kCurveTimeEpsilon || curveT > cache.timeEnd + kCurveTimeEpsilon);
  94. float t = curveT - cache.time;
  95. output = (t * (t * (t * cache.coeff[0] + cache.coeff[1]) + cache.coeff[2])) + cache.coeff[3];
  96. //TODO: IsFinite
  97. // DebugAssertIf (!IsFinite(output));
  98. }
  99. void SetupStepped (float* coeff, const KeyframeTpl<float>& lhs, const KeyframeTpl<float>& rhs)
  100. {
  101. // If either of the tangents in the segment are set to stepped, make the constant value equal the value of the left key
  102. if (lhs.outSlope == std::numeric_limits<float>::infinity() || rhs.inSlope == std::numeric_limits<float>::infinity())
  103. {
  104. coeff[0] = 0.0F;
  105. coeff[1] = 0.0F;
  106. coeff[2] = 0.0F;
  107. coeff[3] = lhs.value;
  108. }
  109. }
  110. void HandleSteppedCurve (const KeyframeTpl<float>& lhs, const KeyframeTpl<float>& rhs, float& value)
  111. {
  112. if (lhs.outSlope == std::numeric_limits<float>::infinity() || rhs.inSlope == std::numeric_limits<float>::infinity())
  113. value = lhs.value;
  114. }
  115. void HandleSteppedTangent (const KeyframeTpl<float>& lhs, const KeyframeTpl<float>& rhs, float& tangent)
  116. {
  117. if (lhs.outSlope == std::numeric_limits<float>::infinity() || rhs.inSlope == std::numeric_limits<float>::infinity())
  118. tangent = std::numeric_limits<float>::infinity();
  119. }
  120. void SetupStepped (Vector3f* coeff, const KeyframeTpl<Vector3f>& lhs, const KeyframeTpl<Vector3f>& rhs)
  121. {
  122. for (int i=0;i<3;i++)
  123. {
  124. // If either of the tangents in the segment are set to stepped, make the constant value equal the value of the left key
  125. if (lhs.outSlope[i] == std::numeric_limits<float>::infinity() || rhs.inSlope[i] == std::numeric_limits<float>::infinity())
  126. {
  127. coeff[0][i] = 0.0F;
  128. coeff[1][i] = 0.0F;
  129. coeff[2][i] = 0.0F;
  130. coeff[3][i] = lhs.value[i];
  131. }
  132. }
  133. }
  134. void HandleSteppedCurve (const KeyframeTpl<Vector3f>& lhs, const KeyframeTpl<Vector3f>& rhs, Vector3f& value)
  135. {
  136. for (int i=0;i<3;i++)
  137. {
  138. if (lhs.outSlope[i] == std::numeric_limits<float>::infinity() || rhs.inSlope[i] == std::numeric_limits<float>::infinity())
  139. value[i] = lhs.value[i];
  140. }
  141. }
  142. void HandleSteppedTangent (const KeyframeTpl<Vector3f>& lhs, const KeyframeTpl<Vector3f>& rhs, Vector3f& value)
  143. {
  144. for (int i=0;i<3;i++)
  145. {
  146. if (lhs.outSlope[i] == std::numeric_limits<float>::infinity() || rhs.inSlope[i] == std::numeric_limits<float>::infinity())
  147. value[i] = std::numeric_limits<float>::infinity();
  148. }
  149. }
  150. void SetupStepped (Quaternionf* coeff, const KeyframeTpl<Quaternionf>& lhs, const KeyframeTpl<Quaternionf>& rhs)
  151. {
  152. // If either of the tangents in the segment are set to stepped, make the constant value equal the value of the left key
  153. if (lhs.outSlope[0] == std::numeric_limits<float>::infinity() || rhs.inSlope[0] == std::numeric_limits<float>::infinity() ||
  154. lhs.outSlope[1] == std::numeric_limits<float>::infinity() || rhs.inSlope[1] == std::numeric_limits<float>::infinity() ||
  155. lhs.outSlope[2] == std::numeric_limits<float>::infinity() || rhs.inSlope[2] == std::numeric_limits<float>::infinity() ||
  156. lhs.outSlope[3] == std::numeric_limits<float>::infinity() || rhs.inSlope[3] == std::numeric_limits<float>::infinity() )
  157. {
  158. for (int i=0;i<4;i++)
  159. {
  160. coeff[0][i] = 0.0F;
  161. coeff[1][i] = 0.0F;
  162. coeff[2][i] = 0.0F;
  163. coeff[3][i] = lhs.value[i];
  164. }
  165. }
  166. }
  167. void HandleSteppedCurve (const KeyframeTpl<Quaternionf>& lhs, const KeyframeTpl<Quaternionf>& rhs, Quaternionf& value)
  168. {
  169. if (lhs.outSlope[0] == std::numeric_limits<float>::infinity() || rhs.inSlope[0] == std::numeric_limits<float>::infinity() ||
  170. lhs.outSlope[1] == std::numeric_limits<float>::infinity() || rhs.inSlope[1] == std::numeric_limits<float>::infinity() ||
  171. lhs.outSlope[2] == std::numeric_limits<float>::infinity() || rhs.inSlope[2] == std::numeric_limits<float>::infinity() ||
  172. lhs.outSlope[3] == std::numeric_limits<float>::infinity() || rhs.inSlope[3] == std::numeric_limits<float>::infinity() )
  173. {
  174. value = lhs.value;
  175. }
  176. }
  177. void HandleSteppedTangent (const KeyframeTpl<Quaternionf>& lhs, const KeyframeTpl<Quaternionf>& rhs, Quaternionf& tangent)
  178. {
  179. for (int i=0;i<4;i++)
  180. {
  181. if (lhs.outSlope[i] == std::numeric_limits<float>::infinity() || rhs.inSlope[i] == std::numeric_limits<float>::infinity())
  182. tangent[i] = std::numeric_limits<float>::infinity();
  183. }
  184. }
  185. template<class T>
  186. void AnimationCurveTpl<T>::CalculateCacheData (Cache& cache, int lhsIndex, int rhsIndex, float timeOffset) const
  187. {
  188. const Keyframe& lhs = m_Curve[lhsIndex];
  189. const Keyframe& rhs = m_Curve[rhsIndex];
  190. // DebugAssertIf (timeOffset < -0.001F || timeOffset - 0.001F > rhs.time - lhs.time);
  191. cache.index = lhsIndex;
  192. cache.time = lhs.time + timeOffset;
  193. cache.timeEnd = rhs.time + timeOffset;
  194. cache.index = lhsIndex;
  195. float dx, length;
  196. T dy;
  197. T m1, m2, d1, d2;
  198. dx = rhs.time - lhs.time;
  199. dx = max(dx, 0.0001F);
  200. dy = rhs.value - lhs.value;
  201. length = 1.0F / (dx * dx);
  202. m1 = lhs.outSlope;
  203. m2 = rhs.inSlope;
  204. d1 = m1 * dx;
  205. d2 = m2 * dx;
  206. cache.coeff[0] = (d1 + d2 - dy - dy) * length / dx;
  207. cache.coeff[1] = (dy + dy + dy - d1 - d1 - d2) * length;
  208. cache.coeff[2] = m1;
  209. cache.coeff[3] = lhs.value;
  210. SetupStepped(cache.coeff, lhs, rhs);
  211. //TODO: IsFinite
  212. // DebugAssertIf(!IsFinite(cache.coeff[0]));
  213. // DebugAssertIf(!IsFinite(cache.coeff[1]));
  214. // DebugAssertIf(!IsFinite(cache.coeff[2]));
  215. // DebugAssertIf(!IsFinite(cache.coeff[3]));
  216. }
  217. // When we look for the next index, how many keyframes do we just loop ahead instead of binary searching?
  218. #define SEARCH_AHEAD 3
  219. ///@TODO: Cleanup old code to completely get rid of this
  220. template<class T>
  221. int AnimationCurveTpl<T>::FindIndex (const Cache& cache, float curveT) const
  222. {
  223. #if SEARCH_AHEAD >= 0
  224. int cacheIndex = cache.index;
  225. if (cacheIndex != -1)
  226. {
  227. // We can not use the cache time or time end since that is in unwrapped time space!
  228. float time = m_Curve[cacheIndex].time;
  229. if (curveT > time)
  230. {
  231. if (cacheIndex + SEARCH_AHEAD < static_cast<int>(m_Curve.size()))
  232. {
  233. for (int i=0;i<SEARCH_AHEAD;i++)
  234. {
  235. if (curveT < m_Curve[cacheIndex + i + 1].time)
  236. return cacheIndex + i;
  237. }
  238. }
  239. }
  240. else
  241. {
  242. if (cacheIndex - SEARCH_AHEAD >= 0)
  243. {
  244. for (int i=0;i<SEARCH_AHEAD;i++)
  245. {
  246. if (curveT > m_Curve[cacheIndex - i - 1].time)
  247. return cacheIndex - i - 1;
  248. }
  249. }
  250. }
  251. }
  252. #endif
  253. ///@ use cache to index into next if not possible use binary search
  254. const_iterator i = std::lower_bound (m_Curve.begin (), m_Curve.end (), curveT, KeyframeCompare());
  255. int index = distance (m_Curve.begin (), i);
  256. index--;
  257. index = min<int> (m_Curve.size () - 2, index);
  258. index = max<int> (0, index);
  259. return index;
  260. }
  261. ///@TODO: Cleanup old code to completely get rid of this
  262. template<class T>
  263. int AnimationCurveTpl<T>::FindIndex (float curveT) const
  264. {
  265. pair<float, float> range = GetRange ();
  266. if (curveT <= range.first || curveT >= range.second)
  267. return -1;
  268. const_iterator i = std::lower_bound (m_Curve.begin (), m_Curve.end (), curveT, KeyframeCompare());
  269. AssertIf (i == m_Curve.end ());
  270. int index = distance (m_Curve.begin (), i);
  271. index--;
  272. index = min<int> (m_Curve.size () - 2, index);
  273. index = max<int> (0, index);
  274. AssertIf (curveT < m_Curve[index].time || curveT > m_Curve[index+1].time);
  275. return index;
  276. }
  277. template<class T>
  278. void AnimationCurveTpl<T>::FindIndexForSampling (const Cache& cache, float curveT, int& lhs, int& rhs) const
  279. {
  280. AssertIf (curveT < GetRange ().first || curveT > GetRange ().second);
  281. int actualSize = m_Curve.size();
  282. const Keyframe* frames = &m_Curve[0];
  283. // Reference implementation:
  284. // (index is the last value that is equal to or smaller than curveT)
  285. #if 0
  286. int foundIndex = 0;
  287. for (int i=0;i<actualSize;i++)
  288. {
  289. if (frames[i].time <= curveT)
  290. foundIndex = i;
  291. }
  292. lhs = foundIndex;
  293. rhs = min<int>(lhs + 1, actualSize - 1);
  294. AssertIf (curveT < m_Curve[lhs].time || curveT > m_Curve[rhs].time);
  295. AssertIf(frames[rhs].time == curveT && frames[lhs].time != curveT)
  296. return;
  297. #endif
  298. #if SEARCH_AHEAD > 0
  299. int cacheIndex = cache.index;
  300. if (cacheIndex != -1)
  301. {
  302. // We can not use the cache time or time end since that is in unwrapped time space!
  303. float time = m_Curve[cacheIndex].time;
  304. if (curveT > time)
  305. {
  306. for (int i=0;i<SEARCH_AHEAD;i++)
  307. {
  308. int index = cacheIndex + i;
  309. if (index + 1 < actualSize && frames[index + 1].time > curveT)
  310. {
  311. lhs = index;
  312. rhs = min<int>(lhs + 1, actualSize - 1);
  313. AssertIf (curveT < frames[lhs].time || curveT > frames[rhs].time);
  314. AssertIf(frames[rhs].time == curveT && frames[lhs].time != curveT);
  315. return;
  316. }
  317. }
  318. }
  319. else
  320. {
  321. for (int i=0;i<SEARCH_AHEAD;i++)
  322. {
  323. int index = cacheIndex - i;
  324. if (index >= 0 && curveT >= frames[index].time)
  325. {
  326. lhs = index;
  327. rhs = min<int>(lhs + 1, actualSize - 1);
  328. AssertIf (curveT < frames[lhs].time || curveT > m_Curve[rhs].time);
  329. AssertIf(frames[rhs].time == curveT && frames[lhs].time != curveT);
  330. return;
  331. }
  332. }
  333. }
  334. }
  335. #endif
  336. // Fall back to using binary search
  337. // upper bound (first value larger than curveT)
  338. int __len = actualSize;
  339. int __half;
  340. int __middle;
  341. int __first = 0;
  342. while (__len > 0)
  343. {
  344. __half = __len >> 1;
  345. __middle = __first + __half;
  346. if (curveT < frames[__middle].time)
  347. __len = __half;
  348. else
  349. {
  350. __first = __middle;
  351. ++__first;
  352. __len = __len - __half - 1;
  353. }
  354. }
  355. // If not within range, we pick the last element twice
  356. lhs = __first - 1;
  357. rhs = min(actualSize - 1, __first);
  358. AssertIf(lhs < 0 || lhs >= actualSize);
  359. AssertIf(rhs < 0 || rhs >= actualSize);
  360. AssertIf (curveT < m_Curve[lhs].time || curveT > m_Curve[rhs].time);
  361. AssertIf(frames[rhs].time == curveT && frames[lhs].time != curveT);
  362. }
  363. template<class T>
  364. void AnimationCurveTpl<T>::SetPreInfinity (int pre)
  365. {
  366. m_PreInfinity = ToInternalInfinity(pre);
  367. InvalidateCache ();
  368. }
  369. template<class T>
  370. void AnimationCurveTpl<T>::SetPostInfinity (int post)
  371. {
  372. m_PostInfinity = ToInternalInfinity(post);
  373. InvalidateCache ();
  374. }
  375. template<class T>
  376. int AnimationCurveTpl<T>::GetPreInfinity () const
  377. {
  378. return FromInternalInfinity(m_PreInfinity);
  379. }
  380. template<class T>
  381. int AnimationCurveTpl<T>::GetPostInfinity () const
  382. {
  383. return FromInternalInfinity(m_PostInfinity);
  384. }
  385. template<class T>
  386. T AnimationCurveTpl<T>::EvaluateClamp (float curveT) const
  387. {
  388. T output;
  389. if (curveT >= m_ClampCache.time && curveT < m_ClampCache.timeEnd)
  390. {
  391. // AssertIf (!CompareApproximately (EvaluateCache (m_Cache, curveT), EvaluateWithoutCache (curveT), 0.001F));
  392. EvaluateCache<T> (m_ClampCache, curveT, output);
  393. return output;
  394. }
  395. else
  396. {
  397. DebugAssertIf (!IsValid ());
  398. float begTime = m_Curve[0].time;
  399. float endTime = m_Curve.back().time;
  400. if (curveT > endTime)
  401. {
  402. m_ClampCache.time = endTime;
  403. m_ClampCache.timeEnd = std::numeric_limits<float>::infinity ();
  404. m_ClampCache.coeff[0] = m_ClampCache.coeff[1] = m_ClampCache.coeff[2] = Zero<T>();
  405. m_ClampCache.coeff[3] = m_Curve[m_Curve.size()-1].value;
  406. }
  407. else if (curveT < begTime)
  408. {
  409. m_ClampCache.time = curveT - 1000.0F;
  410. m_ClampCache.timeEnd = begTime;
  411. m_ClampCache.coeff[0] = m_ClampCache.coeff[1] = m_ClampCache.coeff[2] = Zero<T>();
  412. m_ClampCache.coeff[3] = m_Curve[0].value;
  413. }
  414. else
  415. {
  416. int lhs, rhs;
  417. FindIndexForSampling (m_ClampCache, curveT, lhs, rhs);
  418. CalculateCacheData (m_ClampCache, lhs, rhs, 0.0F);
  419. }
  420. // AssertIf (!CompareApproximately (EvaluateCache (m_Cache, curveT), EvaluateWithoutCache (curveT), 0.001F));
  421. EvaluateCache<T> (m_ClampCache, curveT, output);
  422. return output;
  423. }
  424. }
  425. template<class T>
  426. T AnimationCurveTpl<T>::Evaluate (float curveT) const
  427. {
  428. int lhs, rhs;
  429. T output;
  430. if (curveT >= m_Cache.time && curveT < m_Cache.timeEnd)
  431. {
  432. // AssertIf (!CompareApproximately (EvaluateCache (m_Cache, curveT), EvaluateWithoutCache (curveT), 0.001F));
  433. EvaluateCache<T> (m_Cache, curveT, output);
  434. return output;
  435. }
  436. // @TODO: Optimize IsValid () away if by making the non-valid case always use the m_Cache codepath
  437. else if (IsValid ())
  438. {
  439. float begTime = m_Curve[0].time;
  440. float endTime = m_Curve.back().time;
  441. float wrappedTime;
  442. if (curveT >= endTime)
  443. {
  444. if (m_PostInfinity == kInternalClamp)
  445. {
  446. m_Cache.time = endTime;
  447. m_Cache.timeEnd = std::numeric_limits<float>::infinity ();
  448. m_Cache.coeff[0] = m_Cache.coeff[1] = m_Cache.coeff[2] = Zero<T>();
  449. m_Cache.coeff[3] = m_Curve[m_Curve.size()-1].value;
  450. }
  451. else if (m_PostInfinity == kInternalRepeat)
  452. {
  453. wrappedTime = Repeat (curveT, begTime, endTime);
  454. FindIndexForSampling (m_Cache, wrappedTime, lhs, rhs);
  455. CalculateCacheData (m_Cache, lhs, rhs, curveT - wrappedTime);
  456. }
  457. ///@todo optimize pingpong by making it generate a cache too
  458. else
  459. {
  460. EvaluateWithoutCache (curveT, output);
  461. return output;
  462. }
  463. }
  464. else if (curveT < begTime)
  465. {
  466. if (m_PreInfinity == kInternalClamp)
  467. {
  468. m_Cache.time = curveT - 1000.0F;
  469. m_Cache.timeEnd = begTime;
  470. m_Cache.coeff[0] = m_Cache.coeff[1] = m_Cache.coeff[2] = Zero<T>();
  471. m_Cache.coeff[3] = m_Curve[0].value;
  472. }
  473. else if (m_PreInfinity == kInternalRepeat)
  474. {
  475. wrappedTime = Repeat (curveT, begTime, endTime);
  476. FindIndexForSampling (m_Cache, wrappedTime, lhs, rhs);
  477. CalculateCacheData (m_Cache, lhs, rhs, curveT - wrappedTime);
  478. }
  479. ///@todo optimize pingpong by making it generate a cache too
  480. else
  481. {
  482. EvaluateWithoutCache (curveT, output);
  483. return output;
  484. }
  485. }
  486. else
  487. {
  488. FindIndexForSampling (m_Cache, curveT, lhs, rhs);
  489. CalculateCacheData (m_Cache, lhs, rhs, 0.0F);
  490. }
  491. // AssertIf (!CompareApproximately (EvaluateCache (m_Cache, curveT), EvaluateWithoutCache (curveT), 0.001F));
  492. EvaluateCache<T> (m_Cache, curveT, output);
  493. return output;
  494. }
  495. else
  496. {
  497. if (m_Curve.size () == 1)
  498. return m_Curve.begin()->value;
  499. else
  500. return Zero<T> ();
  501. }
  502. }
  503. template<class T>
  504. float AnimationCurveTpl<T>::WrapTime (float curveT) const
  505. {
  506. DebugAssertIf (!IsValid ());
  507. float begTime = m_Curve[0].time;
  508. float endTime = m_Curve.back().time;
  509. if (curveT < begTime)
  510. {
  511. if (m_PreInfinity == kInternalClamp)
  512. curveT = begTime;
  513. else if (m_PreInfinity == kInternalPingPong)
  514. curveT = PingPong (curveT, begTime, endTime);
  515. else
  516. curveT = Repeat (curveT, begTime, endTime);
  517. }
  518. else if (curveT > endTime)
  519. {
  520. if (m_PostInfinity == kInternalClamp)
  521. curveT = endTime;
  522. else if (m_PostInfinity == kInternalPingPong)
  523. curveT = PingPong (curveT, begTime, endTime);
  524. else
  525. curveT = Repeat (curveT, begTime, endTime);
  526. }
  527. return curveT;
  528. }
  529. template<class T>
  530. int AnimationCurveTpl<T>::AddKey (const Keyframe& key)
  531. {
  532. InvalidateCache ();
  533. iterator i = std::lower_bound (m_Curve.begin (), m_Curve.end (), key);
  534. // is not included in container and value is not a duplicate
  535. if (i == end () || key < *i)
  536. {
  537. iterator ii = m_Curve.insert (i, key);
  538. return std::distance (m_Curve.begin (), ii);
  539. }
  540. else
  541. return -1;
  542. }
  543. template<class T>
  544. void AnimationCurveTpl<T>::RemoveKeys (iterator begin, iterator end)
  545. {
  546. InvalidateCache ();
  547. m_Curve.erase (begin, end);
  548. }
  549. void ScaleCurveValue (AnimationCurve& curve, float scale)
  550. {
  551. for (int i=0;i<curve.GetKeyCount ();i++)
  552. {
  553. curve.GetKey (i).value *= scale;
  554. curve.GetKey (i).inSlope *= scale;
  555. curve.GetKey (i).outSlope *= scale;
  556. }
  557. curve.InvalidateCache();
  558. }
  559. void OffsetCurveValue (AnimationCurve& curve, float offset)
  560. {
  561. for (int i=0;i<curve.GetKeyCount ();i++)
  562. curve.GetKey (i).value += offset;
  563. curve.InvalidateCache();
  564. }
  565. void ScaleCurveTime (AnimationCurve& curve, float scale)
  566. {
  567. for (int i=0;i<curve.GetKeyCount ();i++)
  568. {
  569. curve.GetKey (i).time *= scale;
  570. curve.GetKey (i).inSlope /= scale;
  571. curve.GetKey (i).outSlope /= scale;
  572. }
  573. curve.InvalidateCache();
  574. }
  575. void OffsetCurveTime (AnimationCurve& curve, float offset)
  576. {
  577. for (int i=0;i<curve.GetKeyCount ();i++)
  578. curve.GetKey (i).time += offset;
  579. curve.InvalidateCache();
  580. }
  581. /*
  582. Calculating tangents from a hermite spline () Realtime rendering page 56
  583. > On this first pass we're stuck with linear keyframing, because we just
  584. > don't have the cycles in game to go to splines. I know this would help a
  585. > lot, but it isn't an option.
  586. In Granny I do successive least-squares approximations do the data. I
  587. take the array of samples for a given channel (ie., position) which is 2x
  588. oversampled or better from the art tool. I then start by doing a
  589. least-square solve for a spline of arbitrary degree with knots at either
  590. end. I compute the error over the spline from the original samples, and
  591. add knots in the areas of highest error. Repeat and salt to taste.
  592. Since it's fairly easy to write a single solver that solves for any degree
  593. of spline, I use the same solver for linear keyframes as I do for
  594. quadratic keyframes, cubic keyframes, or even "0th order keframes", which
  595. is to say if you don't want to interpolate _at all_, the solver can still
  596. place the "stop-motion" key frames in the best locations. But hopefully
  597. no one is still doing that kind of animation.
  598. If I were doing this over again (which I probably will at some point), I
  599. would probably use some kind of weird waveletty scheme now. I decided not
  600. to do that originally, because I had about a month to do the entire
  601. spline/solver/reduction thing the first time, and it had to be highly
  602. optimized. So I didn't want to have to learn wavelets and spline solvers
  603. at the same time. Next time I'll spend some time on wavelets and probably
  604. use some sort of hierachical reduction scheme instead, primarily so you
  605. can change how densely your keyframes are placed at run-time, and so you
  606. can get hard edges easier (motions which are intended to have sharp
  607. discontinuities aren't handled well at all by my current scheme).
  608. - Casey
  609. --
  610. > Is anybody looking at the way errors add up? eg. if you do some
  611. > reduction on the hip, and the thigh, and the ankle bone channels, the
  612. > result is a foot that moves quite a bit differently than it should.
  613. This has been on my list for a long time. I don't think it's a simple
  614. case of error analysis though. I think it's more a case for using
  615. discrete skeletal changes or integrated IK, because hey, if what you care
  616. about is having a particular thing stay in one place, then it seems to me
  617. that the best way to compress that is by just saying "this stays in one
  618. place", rather than trying to spend a lot of data on the joint curves
  619. necessary to make that so.
  620. > Also, is anybody doing things like using IK in the reducer, to make sure
  621. > that even in the reduced version the feet stay in exactly the same spot?
  622. That doesn't work with splines, unfortunately, because the splines are
  623. continuous, and you will always have the feet slipping as a result (if not
  624. at the keyframes, then in between for sure). So you end up with the
  625. problem that the IK reducer would need to shove a metric assload of keys
  626. into the streams, which defeats the compression.
  627. From Ian:
  628. > You said you are doing this on linear data as well. I can see that this
  629. > would work, but do you find you get a fairly minimal result? I can
  630. > envisage cases where you'd get many unneeded keyframes from initial
  631. > 'breaks' at points of large error.
  632. I'm not sure what you mean by this. The error is controllable, so you say
  633. how much you are willing to accept. You get a minimal spline for the
  634. error that you ask for, but no more - obviously in the areas of high
  635. error, it has to add more keys, but that's what you want. The objective
  636. of compression, at least in my opinion, is not to remove detail, but
  637. rather to more efficiently store places where there is less detail.
  638. > I think I may be missing the point. Do you do least squares on the
  639. > already fitted cures (ie, a chi squared test) then curve fit separately,
  640. > or do you use least squares to fit your actual spline to the data?
  641. The latter. The incremental knot addition sets up the t_n's of an
  642. arbitrary degree spline. You have a matrix A that has sample-count rows
  643. and knot-count columns. The vector you're looking for is x, the spline
  644. vector, which has knot-count rows. You're producing b, the vector of
  645. samples, which has sample-count rows. So it's Ax = b, but A is
  646. rectangular. You solve via A^T Ax = A^Tb, a simple least squares problem.
  647. You can solve it any way you like. I chose a straightforward
  648. implementation, because there's no numerical difficulties with these
  649. things.
  650. The version that comes with Granny is a highly optimized A^T Ax = A^Tb
  651. solver, which constructs A^T A and A^T b directly and sparsely (so it is
  652. O(n) in the number of samples, instead of O(n^3)). The A^T A is band
  653. diagonal, because of the sparsity pattern of A, so I use a sparse banded
  654. cholesky solver on the back end. It's _extremely_ fast. In fact, the
  655. stupid part of Granny's solver is actually the other part (the error
  656. analysis + knot addition), because it adds very few knots per cycle, so on
  657. a really long animation it can call the least-squares Ax = b solver many
  658. hundreds of times for a single animation, and it _still_ never takes more
  659. than 10 seconds or so even on animations with many hundred frames. So
  660. really, the right place to fix currently is the stupid knot addition
  661. alogirithm, which really should be improved quite a bit.
  662. > I have not used least squared before and from the reading I have done
  663. > (numerical recipes, last night), it seem that the equation of the
  664. > line/spline are inherent in the method and it needs to be reformulated
  665. > to use a different line/spline. (The version I read was for fitting a
  666. > straight line to a data-set, which I know won't work for quaternions
  667. > slerps anyway)
  668. Quaternion lerps are great, and work great with splines. I use them
  669. throughout all of Granny - there is no slerping anywhere. Slerping is not
  670. a very useful thing in a run-time engine, in my opinion, unless you are
  671. dealing with orientations that are greater the 90 degrees apart. It
  672. allows me to use the same solver for position, rotation, AND scale/shear,
  673. with no modifications.
  674. - Casey
  675. -----
  676. > When is it best to use quaternions and when to use normal matrix
  677. > rotations?
  678. In Granny, I use quaternions for everything except the final composite
  679. phase where rotations (and everything else) are multiplied by their
  680. parents to produce the final world-space results. Since we support
  681. scale/shear, orientation, and position, it tends to be fastest at the
  682. composition stage to convert the orientation from quaternion to matrix,
  683. and then do all the matrix concatenation together. I'm not sure I would
  684. do the same if I didn't support scale/shear. It might be a bit more fun
  685. and efficient to go ahead and do the whole pipe in quaternion and only
  686. convert to matrices at the very end (maybe somebody else has played with
  687. that and can comment?)
  688. > And for character animation with moving joints quaternions is usually
  689. > used, but why?
  690. There's lots of nice things about quaternions:
  691. 1) You can treat the linearly if you want to (so you can blend animations
  692. quickly and easily)
  693. 2) You can treat them non-linearly if you want to (so you can do exact
  694. geodesic interpolation at a constant speed)
  695. 3) You can convert them to a matrix with no transcendentals
  696. 4) They are compact, and can be easily converted to a 3-element
  697. representation when necessary (ie., any one of the four values can be
  698. easily re-generated from the other 3)
  699. 5) They cover 720 degrees of rotation, not 360 (if you do a lot of work
  700. with character animation, you will appreciate this!), and the
  701. neighborhooding operator is extremely simple and fast (inner product and a
  702. negation)
  703. 6) They are easy to visualize (they're not much more complicated than
  704. angle/axis) and manipulate (ie., the axis of rotation is obvious, you can
  705. transform the axis of rotation without changing the amount of rotation,
  706. and even just use a regular 3-vector transform, etc.)
  707. 7) You can easily transform vectors with them without converting to a
  708. matrix if you want to
  709. 8) They are easy to renormalize, and they can never become "unorthogonal"
  710. 9) No gimbal lock
  711. 10) There is a simple, fast, and relevant distance metric (the inner
  712. product)
  713. > Is it just by trial and error that we decide when we have to use
  714. > quarternions?
  715. Well, I can't speak for everyone, but I have been extremely careful in my
  716. selection of quaternions. With Granny 1 I did quaternions to get some
  717. practice with them, but when I did 2 I did a lot of research and wrote
  718. code to visualize the actions of various rotational representations and
  719. operations, and I can very confidently say there's no better choice for
  720. general character animation than quaternions, at least among the
  721. representations that I know (euler, angle/axis, matrix, quaternion, exp
  722. map). There are some other mappings that I've come across since I worked
  723. everything out (like the Rational Map), that I have not experimented with,
  724. because so far quaternions have been working superbly so I haven't had
  725. much cause to go hunting.
  726. > "Quarternions have the ability to have smooth interpollated rotations",
  727. > I've made smooth interpollated rotations with normal matrix rotations
  728. > though.
  729. Well, it's not so much what you can do as how easy it is to do it.
  730. Quaternions can be interpolated directly as a smooth geodesic (via slerp)
  731. or via a nonlinear geodesic (lerp). The latter is particularly powerful
  732. because it distributes - it's a linear operator. So you can literally
  733. plug it in to anything that would work, like splines, multi-point blends,
  734. etc., and it will "just work" (well, that's a bit of an exaggeration,
  735. because there is a neighborhooding concern, but it's always easy to do).
  736. > "They take less room, 4 elements versus 9 and some operations
  737. > are cheaper in terms of CPU cycles". I accept this reason except someone
  738. > said that quarternions use more CPU cycles, so I'm not sure who to
  739. > believe.
  740. It depends what you're doing. Quaternions take more CPU cycles to
  741. transform a vector than a matrix does. But quaternions are MUCH less
  742. expensive for lots of other operations, like, for example, splining.
  743. This is why it's very useful to use quaternions for everything except the
  744. final stage of your pipe, where matrices are more appropriate.
  745. > "Quarternions are not susceptible to gimbal lock. Gimbal lock shows its
  746. > face when two axes point in the same direction." So if no axes face in
  747. > the same direction then this is not a reason to use quarternions.
  748. > ...
  749. > Am I right in saying that if no axes face the same direction it is
  750. > possible to represent all rotations with normal matrix rotations?
  751. Matrix rotations are not subject to gimbal lock. That's Euler angles.
  752. - Casey
  753. Least squares is very simple. Given a set of data points (2x oversampled in caseys case) and a knot vector, compute the coefficients for the control points of the spline that minimize squared error. This involves solving a linear system where each row corresponds to a data point (di - they are uniformly space so each point has a corresponding ti which is in the domain of the curve) and each column corresponds to a control point for the curve (cj the unkowns). So matrix element Aij is Bj(ti) where Bj is the basis function for the jth control point. The right hand side is just a vector of the di and the x's are the unkown control points. Sine you are compressing things there will be many more rows then columns in this linear system so you don't have to worry about over fitting problems (which you would if there were more DOF...)
  754. -Peter-Pike
  755. -----Original Message-----
  756. From: Ian Elsley [mailto:ielsley@kushgames.com]
  757. Sent: Tue 12/17/2002 10:35 AM
  758. To: gdalgorithms-list@lists.sourceforge.net
  759. Cc:
  760. Subject: RE: [Algorithms] Re: Keyframe reduction
  761. Casey
  762. I think I may be missing the point. Do you do least squares on the
  763. already fitted cures (ie, a chi squared test) then curve fit separately,
  764. or do you use least squares to fit your actual spline to the data?
  765. I have not used least squared before and from the reading I have done
  766. (numerical recipes, last night), it seem that the equation of the
  767. line/spline are inherent in the method and it needs to be reformulated
  768. to use a different line/spline. (The version I read was for fitting a
  769. straight line to a data-set, which I know won't work for quaternions
  770. slerps anyway)
  771. I see the elegance of this method and would love to work it out, but
  772. I've got a few blanks here.
  773. Any pointers?
  774. Thanks in advance,
  775. Ian
  776. q
  777. q' = -----
  778. |q|
  779. For renormalizing, since you are very close to 1, I usually use the
  780. tangent-line approximation, which was suggested by Checker a long long
  781. time ago for 3D vectors and works just peachy for 4D ones as well:
  782. inline void NormalizeCloseToOne4(float *Dest)
  783. {
  784. float const Sum = (Dest[0] * Dest[0] +
  785. Dest[1] * Dest[1] +
  786. Dest[2] * Dest[2] +
  787. Dest[3] * Dest[3]);
  788. float const ApproximateOneOverRoot = (3.0f - Sum) * 0.5f;
  789. Dest[0] *= ApproximateOneOverRoot;
  790. Dest[1] *= ApproximateOneOverRoot;
  791. Dest[2] *= ApproximateOneOverRoot;
  792. Dest[3] *= ApproximateOneOverRoot;
  793. }
  794. */
  795. #define INSTANTIATE(T) \
  796. template EXPORT_COREMODULE std::pair<float, float> AnimationCurveTpl<T>::GetRange() const; \
  797. template EXPORT_COREMODULE T AnimationCurveTpl<T>::Evaluate (float curveT) const; \
  798. template EXPORT_COREMODULE void AnimationCurveTpl<T>::RemoveKeys (iterator begin, iterator end);\
  799. template EXPORT_COREMODULE int AnimationCurveTpl<T>::AddKey (const Keyframe& key);\
  800. template EXPORT_COREMODULE int AnimationCurveTpl<T>::FindIndex (float time) const; \
  801. template EXPORT_COREMODULE int AnimationCurveTpl<T>::FindIndex (const Cache& cache, float time) const; \
  802. template EXPORT_COREMODULE void AnimationCurveTpl<T>::InvalidateCache (); \
  803. template EXPORT_COREMODULE void AnimationCurveTpl<T>::SetPreInfinity (int mode); \
  804. template EXPORT_COREMODULE void AnimationCurveTpl<T>::SetPostInfinity (int mode); \
  805. template EXPORT_COREMODULE int AnimationCurveTpl<T>::GetPreInfinity () const; \
  806. template EXPORT_COREMODULE int AnimationCurveTpl<T>::GetPostInfinity () const; \
  807. template EXPORT_COREMODULE KeyframeTpl<T>::KeyframeTpl (float time, const T& value);
  808. INSTANTIATE(float)
  809. INSTANTIATE(Vector3f)
  810. INSTANTIATE(Quaternionf)
  811. template EXPORT_COREMODULE void AnimationCurveTpl<float>::CalculateCacheData (Cache& cache, int lhs, int rhs, float timeOffset) const;
  812. template EXPORT_COREMODULE float AnimationCurveTpl<float>::EvaluateClamp (float curveT) const;
  813. template EXPORT_COREMODULE Quaternionf AnimationCurveTpl<Quaternionf>::EvaluateClamp (float curveT) const;
  814. template EXPORT_COREMODULE Vector3f AnimationCurveTpl<Vector3f>::EvaluateClamp (float curveT) const;
  815. NS_RRP_END