GeometryAnimationUsingKeyFrames.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Globalization;
  6. using System.Text.RegularExpressions;
  7. using System.Windows;
  8. using System.Windows.Markup;
  9. using System.Windows.Media;
  10. using System.Windows.Media.Animation;
  11. using HandyControl.Tools;
  12. // ReSharper disable PossibleInvalidOperationException
  13. namespace HandyControl.Media.Animation;
  14. [ContentProperty("KeyFrames")]
  15. public class GeometryAnimationUsingKeyFrames : GeometryAnimationBase, IKeyFrameAnimation, IAddChild
  16. {
  17. private string[] _strings;
  18. public string[] Strings
  19. {
  20. get
  21. {
  22. if (_keyFrames == null || _keyFrames.Count == 0)
  23. {
  24. return null;
  25. }
  26. return _strings ??= Regex.Split(_keyFrames[0].Value.ToString(CultureInfo.InvariantCulture), RegexPatterns.DigitsPattern);
  27. }
  28. }
  29. private GeometryKeyFrameCollection _keyFrames;
  30. private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames;
  31. private bool _areKeyTimesValid;
  32. public GeometryAnimationUsingKeyFrames()
  33. {
  34. _areKeyTimesValid = true;
  35. }
  36. public new GeometryAnimationUsingKeyFrames Clone() => (GeometryAnimationUsingKeyFrames) base.Clone();
  37. public new GeometryAnimationUsingKeyFrames CloneCurrentValue() => (GeometryAnimationUsingKeyFrames) base.CloneCurrentValue();
  38. protected override bool FreezeCore(bool isChecking)
  39. {
  40. var canFreeze = base.FreezeCore(isChecking);
  41. canFreeze &= Freeze(_keyFrames, isChecking);
  42. if (canFreeze & !_areKeyTimesValid)
  43. {
  44. ResolveKeyTimes();
  45. }
  46. return canFreeze;
  47. }
  48. protected override void OnChanged()
  49. {
  50. _areKeyTimesValid = false;
  51. base.OnChanged();
  52. }
  53. protected override Freezable CreateInstanceCore() => new GeometryAnimationUsingKeyFrames();
  54. protected override void CloneCore(Freezable sourceFreezable)
  55. {
  56. var sourceAnimation = (GeometryAnimationUsingKeyFrames) sourceFreezable;
  57. base.CloneCore(sourceFreezable);
  58. CopyCommon(sourceAnimation, false);
  59. }
  60. protected override void CloneCurrentValueCore(Freezable sourceFreezable)
  61. {
  62. var sourceAnimation = (GeometryAnimationUsingKeyFrames) sourceFreezable;
  63. base.CloneCurrentValueCore(sourceFreezable);
  64. CopyCommon(sourceAnimation, true);
  65. }
  66. protected override void GetAsFrozenCore(Freezable source)
  67. {
  68. var sourceAnimation = (GeometryAnimationUsingKeyFrames) source;
  69. base.GetAsFrozenCore(source);
  70. CopyCommon(sourceAnimation, false);
  71. }
  72. protected override void GetCurrentValueAsFrozenCore(Freezable source)
  73. {
  74. var sourceAnimation = (GeometryAnimationUsingKeyFrames) source;
  75. base.GetCurrentValueAsFrozenCore(source);
  76. CopyCommon(sourceAnimation, true);
  77. }
  78. private void CopyCommon(GeometryAnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone)
  79. {
  80. _areKeyTimesValid = sourceAnimation._areKeyTimesValid;
  81. if (_areKeyTimesValid && sourceAnimation._sortedResolvedKeyFrames != null)
  82. {
  83. _sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[]) sourceAnimation._sortedResolvedKeyFrames.Clone();
  84. }
  85. if (sourceAnimation._keyFrames != null)
  86. {
  87. if (isCurrentValueClone)
  88. {
  89. _keyFrames = (GeometryKeyFrameCollection) sourceAnimation._keyFrames.CloneCurrentValue();
  90. }
  91. else
  92. {
  93. _keyFrames = sourceAnimation._keyFrames.Clone();
  94. }
  95. OnFreezablePropertyChanged(null, _keyFrames);
  96. }
  97. }
  98. void IAddChild.AddChild(object child)
  99. {
  100. WritePreamble();
  101. if (child == null)
  102. {
  103. throw new ArgumentNullException(nameof(child));
  104. }
  105. AddChild(child);
  106. WritePostscript();
  107. }
  108. [EditorBrowsable(EditorBrowsableState.Advanced)]
  109. protected virtual void AddChild(object child)
  110. {
  111. if (child is GeometryKeyFrame keyFrame)
  112. {
  113. KeyFrames.Add(keyFrame);
  114. }
  115. else
  116. {
  117. throw new ArgumentException("Animation_ChildMustBeKeyFrame", nameof(child));
  118. }
  119. }
  120. void IAddChild.AddText(string childText)
  121. {
  122. if (childText == null)
  123. {
  124. throw new ArgumentNullException(nameof(childText));
  125. }
  126. AddText(childText);
  127. }
  128. [EditorBrowsable(EditorBrowsableState.Advanced)]
  129. protected virtual void AddText(string childText) => throw new InvalidOperationException("Animation_NoTextChildren");
  130. protected override Geometry GetCurrentValueCore(Geometry defaultOriginValue, Geometry defaultDestinationValue, AnimationClock animationClock)
  131. {
  132. if (_keyFrames == null)
  133. {
  134. return defaultDestinationValue;
  135. }
  136. if (!_areKeyTimesValid)
  137. {
  138. ResolveKeyTimes();
  139. }
  140. if (_sortedResolvedKeyFrames == null)
  141. {
  142. return defaultDestinationValue;
  143. }
  144. var currentTime = animationClock.CurrentTime.Value;
  145. var keyFrameCount = _sortedResolvedKeyFrames.Length;
  146. var maxKeyFrameIndex = keyFrameCount - 1;
  147. double[] currentIterationValue;
  148. var currentResolvedKeyFrameIndex = 0;
  149. while (currentResolvedKeyFrameIndex < keyFrameCount && currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
  150. {
  151. currentResolvedKeyFrameIndex++;
  152. }
  153. while (currentResolvedKeyFrameIndex < maxKeyFrameIndex && currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime)
  154. {
  155. currentResolvedKeyFrameIndex++;
  156. }
  157. if (currentResolvedKeyFrameIndex == keyFrameCount)
  158. {
  159. currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex);
  160. }
  161. else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
  162. {
  163. currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex);
  164. }
  165. else
  166. {
  167. double currentSegmentProgress;
  168. double[] fromValue;
  169. if (currentResolvedKeyFrameIndex == 0)
  170. {
  171. AnimationHelper.DecomposeGeometryStr(defaultOriginValue.ToString(CultureInfo.InvariantCulture), out fromValue);
  172. currentSegmentProgress = currentTime.TotalMilliseconds / _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds;
  173. }
  174. else
  175. {
  176. var previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1;
  177. var previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime;
  178. fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex);
  179. var segmentCurrentTime = currentTime - previousResolvedKeyTime;
  180. var segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime;
  181. currentSegmentProgress = segmentCurrentTime.TotalMilliseconds / segmentDuration.TotalMilliseconds;
  182. }
  183. currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress);
  184. }
  185. return AnimationHelper.ComposeGeometry(Strings, currentIterationValue);
  186. }
  187. protected sealed override Duration GetNaturalDurationCore(Clock clock) => new(LargestTimeSpanKeyTime);
  188. IList IKeyFrameAnimation.KeyFrames
  189. {
  190. get => KeyFrames;
  191. set => KeyFrames = (GeometryKeyFrameCollection) value;
  192. }
  193. public GeometryKeyFrameCollection KeyFrames
  194. {
  195. get
  196. {
  197. ReadPreamble();
  198. if (_keyFrames == null)
  199. {
  200. if (IsFrozen)
  201. {
  202. _keyFrames = GeometryKeyFrameCollection.Empty;
  203. }
  204. else
  205. {
  206. WritePreamble();
  207. _keyFrames = new GeometryKeyFrameCollection();
  208. OnFreezablePropertyChanged(null, _keyFrames);
  209. WritePostscript();
  210. }
  211. }
  212. return _keyFrames;
  213. }
  214. set
  215. {
  216. if (value == null)
  217. {
  218. throw new ArgumentNullException(nameof(value));
  219. }
  220. WritePreamble();
  221. if (value != _keyFrames)
  222. {
  223. OnFreezablePropertyChanged(_keyFrames, value);
  224. _keyFrames = value;
  225. WritePostscript();
  226. }
  227. }
  228. }
  229. [EditorBrowsable(EditorBrowsableState.Never)]
  230. public bool ShouldSerializeKeyFrames()
  231. {
  232. ReadPreamble();
  233. return _keyFrames != null && _keyFrames.Count > 0;
  234. }
  235. private struct KeyTimeBlock
  236. {
  237. public int BeginIndex;
  238. public int EndIndex;
  239. }
  240. private double[] GetResolvedKeyFrameValue(int resolvedKeyFrameIndex) =>
  241. GetResolvedKeyFrame(resolvedKeyFrameIndex).Numbers;
  242. private GeometryKeyFrame GetResolvedKeyFrame(int resolvedKeyFrameIndex) =>
  243. _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex];
  244. private TimeSpan LargestTimeSpanKeyTime
  245. {
  246. get
  247. {
  248. var hasTimeSpanKeyTime = false;
  249. var largestTimeSpanKeyTime = TimeSpan.Zero;
  250. if (_keyFrames != null)
  251. {
  252. var keyFrameCount = _keyFrames.Count;
  253. for (var index = 0; index < keyFrameCount; index++)
  254. {
  255. var keyTime = _keyFrames[index].KeyTime;
  256. if (keyTime.Type == KeyTimeType.TimeSpan)
  257. {
  258. hasTimeSpanKeyTime = true;
  259. if (keyTime.TimeSpan > largestTimeSpanKeyTime)
  260. {
  261. largestTimeSpanKeyTime = keyTime.TimeSpan;
  262. }
  263. }
  264. }
  265. }
  266. return hasTimeSpanKeyTime ? largestTimeSpanKeyTime : TimeSpan.FromSeconds(1.0);
  267. }
  268. }
  269. private void ResolveKeyTimes()
  270. {
  271. var keyFrameCount = 0;
  272. if (_keyFrames != null)
  273. {
  274. keyFrameCount = _keyFrames.Count;
  275. }
  276. if (keyFrameCount == 0)
  277. {
  278. _sortedResolvedKeyFrames = null;
  279. _areKeyTimesValid = true;
  280. return;
  281. }
  282. _sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount];
  283. var index = 0;
  284. for (; index < keyFrameCount; index++)
  285. {
  286. _sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index;
  287. }
  288. var duration = Duration;
  289. var calculationDuration = duration.HasTimeSpan ? duration.TimeSpan : LargestTimeSpanKeyTime;
  290. var maxKeyFrameIndex = keyFrameCount - 1;
  291. var unspecifiedBlocks = new List<KeyTimeBlock>();
  292. var hasPacedKeyTimes = false;
  293. index = 0;
  294. while (index < keyFrameCount)
  295. {
  296. // ReSharper disable once PossibleNullReferenceException
  297. var keyTime = _keyFrames[index].KeyTime;
  298. switch (keyTime.Type)
  299. {
  300. case KeyTimeType.Percent:
  301. _sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds(keyTime.Percent * calculationDuration.TotalMilliseconds);
  302. index++;
  303. break;
  304. case KeyTimeType.TimeSpan:
  305. _sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan;
  306. index++;
  307. break;
  308. case KeyTimeType.Paced:
  309. case KeyTimeType.Uniform:
  310. if (index == maxKeyFrameIndex)
  311. {
  312. _sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration;
  313. index++;
  314. }
  315. else if (index == 0 && keyTime.Type == KeyTimeType.Paced)
  316. {
  317. _sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero;
  318. index++;
  319. }
  320. else
  321. {
  322. if (keyTime.Type == KeyTimeType.Paced)
  323. {
  324. hasPacedKeyTimes = true;
  325. }
  326. var block = new KeyTimeBlock
  327. {
  328. BeginIndex = index
  329. };
  330. while (++index < maxKeyFrameIndex)
  331. {
  332. var type = _keyFrames[index].KeyTime.Type;
  333. if (type == KeyTimeType.Percent || type == KeyTimeType.TimeSpan)
  334. {
  335. break;
  336. }
  337. if (type == KeyTimeType.Paced)
  338. {
  339. hasPacedKeyTimes = true;
  340. }
  341. }
  342. block.EndIndex = index;
  343. unspecifiedBlocks.Add(block);
  344. }
  345. break;
  346. }
  347. }
  348. foreach (var block in unspecifiedBlocks)
  349. {
  350. var blockBeginTime = TimeSpan.Zero;
  351. if (block.BeginIndex > 0)
  352. {
  353. blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime;
  354. }
  355. long segmentCount = block.EndIndex - block.BeginIndex + 1;
  356. var uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount);
  357. index = block.BeginIndex;
  358. var resolvedTime = blockBeginTime + uniformTimeStep;
  359. while (index < block.EndIndex)
  360. {
  361. _sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime;
  362. resolvedTime += uniformTimeStep;
  363. index++;
  364. }
  365. }
  366. if (hasPacedKeyTimes)
  367. {
  368. ResolvePacedKeyTimes();
  369. }
  370. Array.Sort(_sortedResolvedKeyFrames);
  371. _areKeyTimesValid = true;
  372. }
  373. private void ResolvePacedKeyTimes()
  374. {
  375. var index = 1;
  376. var maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1;
  377. do
  378. {
  379. if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced)
  380. {
  381. var firstPacedBlockKeyFrameIndex = index;
  382. var segmentLengths = new List<double>();
  383. var prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime;
  384. var totalLength = 0.0;
  385. var prevKeyValue = _keyFrames[index - 1].Numbers;
  386. do
  387. {
  388. var currentKeyValue = _keyFrames[index].Numbers;
  389. totalLength += Math.Abs(currentKeyValue[0] - prevKeyValue[0]);
  390. segmentLengths.Add(totalLength);
  391. prevKeyValue = currentKeyValue;
  392. index++;
  393. }
  394. while (index < maxKeyFrameIndex && _keyFrames[index].KeyTime.Type == KeyTimeType.Paced);
  395. totalLength += Math.Abs(_keyFrames[index].Numbers[0] - prevKeyValue[0]);
  396. var pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime;
  397. for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++)
  398. {
  399. _sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds(segmentLengths[i] / totalLength * pacedBlockDuration.TotalMilliseconds);
  400. }
  401. }
  402. else
  403. {
  404. index++;
  405. }
  406. }
  407. while (index < maxKeyFrameIndex);
  408. }
  409. }