源战役客户端
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1066 行
42 KiB

  1. /******************************************************************************
  2. * Spine Runtimes Software License v2.5
  3. *
  4. * Copyright (c) 2013-2016, Esoteric Software
  5. * All rights reserved.
  6. *
  7. * You are granted a perpetual, non-exclusive, non-sublicensable, and
  8. * non-transferable license to use, install, execute, and perform the Spine
  9. * Runtimes software and derivative works solely for personal or internal
  10. * use. Without the written permission of Esoteric Software (see Section 2 of
  11. * the Spine Software License Agreement), you may not (a) modify, translate,
  12. * adapt, or develop new applications using the Spine Runtimes or otherwise
  13. * create derivative works or improvements of the Spine Runtimes or (b) remove,
  14. * delete, alter, or obscure any trademarks or any copyright, trademark, patent,
  15. * or other intellectual property or proprietary rights notices on or in the
  16. * Software, including any copy thereof. Redistributions in binary or source
  17. * form must include this license and terms.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
  20. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  21. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  22. * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  24. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
  25. * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  26. * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  27. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. * POSSIBILITY OF SUCH DAMAGE.
  29. *****************************************************************************/
  30. using System;
  31. using System.Collections.Generic;
  32. namespace Spine {
  33. public class AnimationState {
  34. static readonly Animation EmptyAnimation = new Animation("<empty>", new ExposedList<Timeline>(), 0);
  35. internal const int Subsequent = 0, First = 1, Dip = 2, DipMix = 3;
  36. private AnimationStateData data;
  37. Pool<TrackEntry> trackEntryPool = new Pool<TrackEntry>();
  38. private readonly ExposedList<TrackEntry> tracks = new ExposedList<TrackEntry>();
  39. private readonly ExposedList<Event> events = new ExposedList<Event>();
  40. private readonly EventQueue queue; // Initialized by constructor.
  41. private readonly HashSet<int> propertyIDs = new HashSet<int>();
  42. private readonly ExposedList<TrackEntry> mixingTo = new ExposedList<TrackEntry>();
  43. private bool animationsChanged;
  44. private float timeScale = 1;
  45. public AnimationStateData Data { get { return data; } }
  46. /// <summary>A list of tracks that have animations, which may contain nulls.</summary>
  47. public ExposedList<TrackEntry> Tracks { get { return tracks; } }
  48. public float TimeScale { get { return timeScale; } set { timeScale = value; } }
  49. public delegate void TrackEntryDelegate (TrackEntry trackEntry);
  50. public event TrackEntryDelegate Start, Interrupt, End, Dispose, Complete;
  51. public delegate void TrackEntryEventDelegate (TrackEntry trackEntry, Event e);
  52. public event TrackEntryEventDelegate Event;
  53. public AnimationState (AnimationStateData data) {
  54. if (data == null) throw new ArgumentNullException("data", "data cannot be null.");
  55. this.data = data;
  56. this.queue = new EventQueue(
  57. this,
  58. delegate { this.animationsChanged = true; },
  59. trackEntryPool
  60. );
  61. }
  62. /// <summary>
  63. /// Increments the track entry times, setting queued animations as current if needed</summary>
  64. /// <param name="delta">delta time</param>
  65. public void Update (float delta) {
  66. delta *= timeScale;
  67. var tracksItems = tracks.Items;
  68. for (int i = 0, n = tracks.Count; i < n; i++) {
  69. TrackEntry current = tracksItems[i];
  70. if (current == null) continue;
  71. current.animationLast = current.nextAnimationLast;
  72. current.trackLast = current.nextTrackLast;
  73. float currentDelta = delta * current.timeScale;
  74. if (current.delay > 0) {
  75. current.delay -= currentDelta;
  76. if (current.delay > 0) continue;
  77. currentDelta = -current.delay;
  78. current.delay = 0;
  79. }
  80. TrackEntry next = current.next;
  81. if (next != null) {
  82. // When the next entry's delay is passed, change to the next entry, preserving leftover time.
  83. float nextTime = current.trackLast - next.delay;
  84. if (nextTime >= 0) {
  85. next.delay = 0;
  86. next.trackTime = nextTime + (delta * next.timeScale);
  87. current.trackTime += currentDelta;
  88. SetCurrent(i, next, true);
  89. while (next.mixingFrom != null) {
  90. next.mixTime += currentDelta;
  91. next = next.mixingFrom;
  92. }
  93. continue;
  94. }
  95. } else if (current.trackLast >= current.trackEnd && current.mixingFrom == null) {
  96. // Clear the track when there is no next entry, the track end time is reached, and there is no mixingFrom.
  97. tracksItems[i] = null;
  98. queue.End(current);
  99. DisposeNext(current);
  100. continue;
  101. }
  102. if (current.mixingFrom != null && UpdateMixingFrom(current, delta)) {
  103. // End mixing from entries once all have completed.
  104. var from = current.mixingFrom;
  105. current.mixingFrom = null;
  106. while (from != null) {
  107. queue.End(from);
  108. from = from.mixingFrom;
  109. }
  110. }
  111. current.trackTime += currentDelta;
  112. }
  113. queue.Drain();
  114. }
  115. /// <summary>Returns true when all mixing from entries are complete.</summary>
  116. private bool UpdateMixingFrom (TrackEntry to, float delta) {
  117. TrackEntry from = to.mixingFrom;
  118. if (from == null) return true;
  119. bool finished = UpdateMixingFrom(from, delta);
  120. from.animationLast = from.nextAnimationLast;
  121. from.trackLast = from.nextTrackLast;
  122. // Require mixTime > 0 to ensure the mixing from entry was applied at least once.
  123. if (to.mixTime > 0 && (to.mixTime >= to.mixDuration || to.timeScale == 0)) {
  124. // Require totalAlpha == 0 to ensure mixing is complete, unless mixDuration == 0 (the transition is a single frame).
  125. if (from.totalAlpha == 0 || to.mixDuration == 0) {
  126. to.mixingFrom = from.mixingFrom;
  127. to.interruptAlpha = from.interruptAlpha;
  128. queue.End(from);
  129. }
  130. return finished;
  131. }
  132. from.trackTime += delta * from.timeScale;
  133. to.mixTime += delta * to.timeScale;
  134. return false;
  135. }
  136. /// <summary>
  137. /// Poses the skeleton using the track entry animations. There are no side effects other than invoking listeners, so the
  138. /// animation state can be applied to multiple skeletons to pose them identically.</summary>
  139. public bool Apply (Skeleton skeleton) {
  140. if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null.");
  141. if (animationsChanged) AnimationsChanged();
  142. var events = this.events;
  143. bool applied = false;
  144. var tracksItems = tracks.Items;
  145. for (int i = 0, m = tracks.Count; i < m; i++) {
  146. TrackEntry current = tracksItems[i];
  147. if (current == null || current.delay > 0) continue;
  148. applied = true;
  149. MixPose currentPose = i == 0 ? MixPose.Current : MixPose.CurrentLayered;
  150. // Apply mixing from entries first.
  151. float mix = current.alpha;
  152. if (current.mixingFrom != null)
  153. mix *= ApplyMixingFrom(current, skeleton, currentPose);
  154. else if (current.trackTime >= current.trackEnd && current.next == null) //
  155. mix = 0; // Set to setup pose the last time the entry will be applied.
  156. // Apply current entry.
  157. float animationLast = current.animationLast, animationTime = current.AnimationTime;
  158. int timelineCount = current.animation.timelines.Count;
  159. var timelines = current.animation.timelines;
  160. var timelinesItems = timelines.Items;
  161. if (mix == 1) {
  162. for (int ii = 0; ii < timelineCount; ii++)
  163. timelinesItems[ii].Apply(skeleton, animationLast, animationTime, events, 1, MixPose.Setup, MixDirection.In);
  164. } else {
  165. var timelineData = current.timelineData.Items;
  166. bool firstFrame = current.timelinesRotation.Count == 0;
  167. if (firstFrame) current.timelinesRotation.EnsureCapacity(timelines.Count << 1);
  168. var timelinesRotation = current.timelinesRotation.Items;
  169. for (int ii = 0; ii < timelineCount; ii++) {
  170. Timeline timeline = timelinesItems[ii];
  171. MixPose pose = timelineData[ii] >= AnimationState.First ? MixPose.Setup : currentPose;
  172. var rotateTimeline = timeline as RotateTimeline;
  173. if (rotateTimeline != null)
  174. ApplyRotateTimeline(rotateTimeline, skeleton, animationTime, mix, pose, timelinesRotation, ii << 1, firstFrame);
  175. else
  176. timeline.Apply(skeleton, animationLast, animationTime, events, mix, pose, MixDirection.In);
  177. }
  178. }
  179. QueueEvents(current, animationTime);
  180. events.Clear(false);
  181. current.nextAnimationLast = animationTime;
  182. current.nextTrackLast = current.trackTime;
  183. }
  184. queue.Drain();
  185. return applied;
  186. }
  187. private float ApplyMixingFrom (TrackEntry to, Skeleton skeleton, MixPose currentPose) {
  188. TrackEntry from = to.mixingFrom;
  189. if (from.mixingFrom != null) ApplyMixingFrom(from, skeleton, currentPose);
  190. float mix;
  191. if (to.mixDuration == 0) { // Single frame mix to undo mixingFrom changes.
  192. mix = 1;
  193. currentPose = MixPose.Setup;
  194. } else {
  195. mix = to.mixTime / to.mixDuration;
  196. if (mix > 1) mix = 1;
  197. }
  198. var eventBuffer = mix < from.eventThreshold ? this.events : null;
  199. bool attachments = mix < from.attachmentThreshold, drawOrder = mix < from.drawOrderThreshold;
  200. float animationLast = from.animationLast, animationTime = from.AnimationTime;
  201. var timelines = from.animation.timelines;
  202. int timelineCount = timelines.Count;
  203. var timelinesItems = timelines.Items;
  204. var timelineData = from.timelineData.Items;
  205. var timelineDipMix = from.timelineDipMix.Items;
  206. bool firstFrame = from.timelinesRotation.Count == 0;
  207. if (firstFrame) from.timelinesRotation.Resize(timelines.Count << 1); // from.timelinesRotation.setSize
  208. var timelinesRotation = from.timelinesRotation.Items;
  209. MixPose pose;
  210. float alphaDip = from.alpha * to.interruptAlpha, alphaMix = alphaDip * (1 - mix), alpha;
  211. from.totalAlpha = 0;
  212. for (int i = 0; i < timelineCount; i++) {
  213. Timeline timeline = timelinesItems[i];
  214. switch (timelineData[i]) {
  215. case Subsequent:
  216. if (!attachments && timeline is AttachmentTimeline) continue;
  217. if (!drawOrder && timeline is DrawOrderTimeline) continue;
  218. pose = currentPose;
  219. alpha = alphaMix;
  220. break;
  221. case First:
  222. pose = MixPose.Setup;
  223. alpha = alphaMix;
  224. break;
  225. case Dip:
  226. pose = MixPose.Setup;
  227. alpha = alphaDip;
  228. break;
  229. default:
  230. pose = MixPose.Setup;
  231. TrackEntry dipMix = timelineDipMix[i];
  232. alpha = alphaDip * Math.Max(0, 1 - dipMix.mixTime / dipMix.mixDuration);
  233. break;
  234. }
  235. from.totalAlpha += alpha;
  236. var rotateTimeline = timeline as RotateTimeline;
  237. if (rotateTimeline != null) {
  238. ApplyRotateTimeline(rotateTimeline, skeleton, animationTime, alpha, pose, timelinesRotation, i << 1, firstFrame);
  239. } else {
  240. timeline.Apply(skeleton, animationLast, animationTime, eventBuffer, alpha, pose, MixDirection.Out);
  241. }
  242. }
  243. if (to.mixDuration > 0) QueueEvents(from, animationTime);
  244. this.events.Clear(false);
  245. from.nextAnimationLast = animationTime;
  246. from.nextTrackLast = from.trackTime;
  247. return mix;
  248. }
  249. static private void ApplyRotateTimeline (RotateTimeline rotateTimeline, Skeleton skeleton, float time, float alpha, MixPose pose,
  250. float[] timelinesRotation, int i, bool firstFrame) {
  251. if (firstFrame) timelinesRotation[i] = 0;
  252. if (alpha == 1) {
  253. rotateTimeline.Apply(skeleton, 0, time, null, 1, pose, MixDirection.In);
  254. return;
  255. }
  256. Bone bone = skeleton.bones.Items[rotateTimeline.boneIndex];
  257. float[] frames = rotateTimeline.frames;
  258. if (time < frames[0]) {
  259. if (pose == MixPose.Setup) bone.rotation = bone.data.rotation;
  260. return;
  261. }
  262. float r2;
  263. if (time >= frames[frames.Length - RotateTimeline.ENTRIES]) // Time is after last frame.
  264. r2 = bone.data.rotation + frames[frames.Length + RotateTimeline.PREV_ROTATION];
  265. else {
  266. // Interpolate between the previous frame and the current frame.
  267. int frame = Animation.BinarySearch(frames, time, RotateTimeline.ENTRIES);
  268. float prevRotation = frames[frame + RotateTimeline.PREV_ROTATION];
  269. float frameTime = frames[frame];
  270. float percent = rotateTimeline.GetCurvePercent((frame >> 1) - 1,
  271. 1 - (time - frameTime) / (frames[frame + RotateTimeline.PREV_TIME] - frameTime));
  272. r2 = frames[frame + RotateTimeline.ROTATION] - prevRotation;
  273. r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360;
  274. r2 = prevRotation + r2 * percent + bone.data.rotation;
  275. r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360;
  276. }
  277. // Mix between rotations using the direction of the shortest route on the first frame while detecting crosses.
  278. float r1 = pose == MixPose.Setup ? bone.data.rotation : bone.rotation;
  279. float total, diff = r2 - r1;
  280. if (diff == 0) {
  281. total = timelinesRotation[i];
  282. } else {
  283. diff -= (16384 - (int)(16384.499999999996 - diff / 360)) * 360;
  284. float lastTotal, lastDiff;
  285. if (firstFrame) {
  286. lastTotal = 0;
  287. lastDiff = diff;
  288. } else {
  289. lastTotal = timelinesRotation[i]; // Angle and direction of mix, including loops.
  290. lastDiff = timelinesRotation[i + 1]; // Difference between bones.
  291. }
  292. bool current = diff > 0, dir = lastTotal >= 0;
  293. // Detect cross at 0 (not 180).
  294. if (Math.Sign(lastDiff) != Math.Sign(diff) && Math.Abs(lastDiff) <= 90) {
  295. // A cross after a 360 rotation is a loop.
  296. if (Math.Abs(lastTotal) > 180) lastTotal += 360 * Math.Sign(lastTotal);
  297. dir = current;
  298. }
  299. total = diff + lastTotal - lastTotal % 360; // Store loops as part of lastTotal.
  300. if (dir != current) total += 360 * Math.Sign(lastTotal);
  301. timelinesRotation[i] = total;
  302. }
  303. timelinesRotation[i + 1] = diff;
  304. r1 += total * alpha;
  305. bone.rotation = r1 - (16384 - (int)(16384.499999999996 - r1 / 360)) * 360;
  306. }
  307. private void QueueEvents (TrackEntry entry, float animationTime) {
  308. float animationStart = entry.animationStart, animationEnd = entry.animationEnd;
  309. float duration = animationEnd - animationStart;
  310. float trackLastWrapped = entry.trackLast % duration;
  311. // Queue events before complete.
  312. var events = this.events;
  313. var eventsItems = events.Items;
  314. int i = 0, n = events.Count;
  315. for (; i < n; i++) {
  316. var e = eventsItems[i];
  317. if (e.time < trackLastWrapped) break;
  318. if (e.time > animationEnd) continue; // Discard events outside animation start/end.
  319. queue.Event(entry, e);
  320. }
  321. // Queue complete if completed a loop iteration or the animation.
  322. bool complete = false;
  323. if (entry.loop)
  324. complete = duration == 0 || (trackLastWrapped > entry.trackTime % duration);
  325. else
  326. complete = animationTime >= animationEnd && entry.animationLast < animationEnd;
  327. if (complete) queue.Complete(entry);
  328. // Queue events after complete.
  329. for (; i < n; i++) {
  330. Event e = eventsItems[i];
  331. if (e.time < animationStart) continue; // Discard events outside animation start/end.
  332. queue.Event(entry, eventsItems[i]);
  333. }
  334. }
  335. /// <summary>
  336. /// Removes all animations from all tracks, leaving skeletons in their previous pose.
  337. /// It may be desired to use <see cref="AnimationState.SetEmptyAnimations(float)"/> to mix the skeletons back to the setup pose,
  338. /// rather than leaving them in their previous pose.</summary>
  339. public void ClearTracks () {
  340. bool oldDrainDisabled = queue.drainDisabled;
  341. queue.drainDisabled = true;
  342. for (int i = 0, n = tracks.Count; i < n; i++) {
  343. ClearTrack(i);
  344. }
  345. tracks.Clear();
  346. queue.drainDisabled = oldDrainDisabled;
  347. queue.Drain();
  348. }
  349. /// <summary>
  350. /// Removes all animations from the tracks, leaving skeletons in their previous pose.
  351. /// It may be desired to use <see cref="AnimationState.SetEmptyAnimations(float)"/> to mix the skeletons back to the setup pose,
  352. /// rather than leaving them in their previous pose.</summary>
  353. public void ClearTrack (int trackIndex) {
  354. if (trackIndex >= tracks.Count) return;
  355. TrackEntry current = tracks.Items[trackIndex];
  356. if (current == null) return;
  357. queue.End(current);
  358. DisposeNext(current);
  359. TrackEntry entry = current;
  360. while (true) {
  361. TrackEntry from = entry.mixingFrom;
  362. if (from == null) break;
  363. queue.End(from);
  364. entry.mixingFrom = null;
  365. entry = from;
  366. }
  367. tracks.Items[current.trackIndex] = null;
  368. queue.Drain();
  369. }
  370. /// <summary>Sets the active TrackEntry for a given track number.</summary>
  371. private void SetCurrent (int index, TrackEntry current, bool interrupt) {
  372. TrackEntry from = ExpandToIndex(index);
  373. tracks.Items[index] = current;
  374. if (from != null) {
  375. if (interrupt) queue.Interrupt(from);
  376. current.mixingFrom = from;
  377. current.mixTime = 0;
  378. // Store interrupted mix percentage.
  379. if (from.mixingFrom != null && from.mixDuration > 0)
  380. current.interruptAlpha *= Math.Min(1, from.mixTime / from.mixDuration);
  381. from.timelinesRotation.Clear(); // Reset rotation for mixing out, in case entry was mixed in.
  382. }
  383. queue.Start(current); // triggers AnimationsChanged
  384. }
  385. /// <summary>Sets an animation by name. <seealso cref="SetAnimation(int, Animation, bool)" /></summary>
  386. public TrackEntry SetAnimation (int trackIndex, string animationName, bool loop) {
  387. Animation animation = data.skeletonData.FindAnimation(animationName);
  388. if (animation == null) throw new ArgumentException("Animation not found: " + animationName, "animationName");
  389. return SetAnimation(trackIndex, animation, loop);
  390. }
  391. /// <summary>Sets the current animation for a track, discarding any queued animations.</summary>
  392. /// <param name="loop">If true, the animation will repeat.
  393. /// If false, it will not, instead its last frame is applied if played beyond its duration.
  394. /// In either case <see cref="TrackEntry.TrackEnd"/> determines when the track is cleared. </param>
  395. /// <returns>
  396. /// A track entry to allow further customization of animation playback. References to the track entry must not be kept
  397. /// after <see cref="AnimationState.Dispose"/>.</returns>
  398. public TrackEntry SetAnimation (int trackIndex, Animation animation, bool loop) {
  399. if (animation == null) throw new ArgumentNullException("animation", "animation cannot be null.");
  400. bool interrupt = true;
  401. TrackEntry current = ExpandToIndex(trackIndex);
  402. if (current != null) {
  403. if (current.nextTrackLast == -1) {
  404. // Don't mix from an entry that was never applied.
  405. tracks.Items[trackIndex] = current.mixingFrom;
  406. queue.Interrupt(current);
  407. queue.End(current);
  408. DisposeNext(current);
  409. current = current.mixingFrom;
  410. interrupt = false;
  411. } else {
  412. DisposeNext(current);
  413. }
  414. }
  415. TrackEntry entry = NewTrackEntry(trackIndex, animation, loop, current);
  416. SetCurrent(trackIndex, entry, interrupt);
  417. queue.Drain();
  418. return entry;
  419. }
  420. /// <summary>Queues an animation by name.</summary>
  421. /// <seealso cref="AddAnimation(int, Animation, bool, float)" />
  422. public TrackEntry AddAnimation (int trackIndex, string animationName, bool loop, float delay) {
  423. Animation animation = data.skeletonData.FindAnimation(animationName);
  424. if (animation == null) throw new ArgumentException("Animation not found: " + animationName, "animationName");
  425. return AddAnimation(trackIndex, animation, loop, delay);
  426. }
  427. /// <summary>Adds an animation to be played delay seconds after the current or last queued animation
  428. /// for a track. If the track is empty, it is equivalent to calling <see cref="SetAnimation"/>.</summary>
  429. /// <param name="delay">
  430. /// Seconds to begin this animation after the start of the previous animation. May be &lt;= 0 to use the animation
  431. /// duration of the previous track minus any mix duration plus the negative delay.
  432. /// </param>
  433. /// <returns>A track entry to allow further customization of animation playback. References to the track entry must not be kept
  434. /// after <see cref="AnimationState.Dispose"/></returns>
  435. public TrackEntry AddAnimation (int trackIndex, Animation animation, bool loop, float delay) {
  436. if (animation == null) throw new ArgumentNullException("animation", "animation cannot be null.");
  437. TrackEntry last = ExpandToIndex(trackIndex);
  438. if (last != null) {
  439. while (last.next != null)
  440. last = last.next;
  441. }
  442. TrackEntry entry = NewTrackEntry(trackIndex, animation, loop, last);
  443. if (last == null) {
  444. SetCurrent(trackIndex, entry, true);
  445. queue.Drain();
  446. } else {
  447. last.next = entry;
  448. if (delay <= 0) {
  449. float duration = last.animationEnd - last.animationStart;
  450. if (duration != 0) {
  451. if (last.loop) {
  452. delay += duration * (1 + (int)(last.trackTime / duration));
  453. } else {
  454. delay += duration;
  455. }
  456. delay -= data.GetMix(last.animation, animation);
  457. } else
  458. delay = 0;
  459. }
  460. }
  461. entry.delay = delay;
  462. return entry;
  463. }
  464. /// <summary>
  465. /// Sets an empty animation for a track, discarding any queued animations, and mixes to it over the specified mix duration.</summary>
  466. public TrackEntry SetEmptyAnimation (int trackIndex, float mixDuration) {
  467. TrackEntry entry = SetAnimation(trackIndex, AnimationState.EmptyAnimation, false);
  468. entry.mixDuration = mixDuration;
  469. entry.trackEnd = mixDuration;
  470. return entry;
  471. }
  472. /// <summary>
  473. /// Adds an empty animation to be played after the current or last queued animation for a track, and mixes to it over the
  474. /// specified mix duration.</summary>
  475. /// <returns>
  476. /// A track entry to allow further customization of animation playback. References to the track entry must not be kept after <see cref="AnimationState.Dispose"/>.
  477. /// </returns>
  478. /// <param name="trackIndex">Track number.</param>
  479. /// <param name="mixDuration">Mix duration.</param>
  480. /// <param name="delay">Seconds to begin this animation after the start of the previous animation. May be &lt;= 0 to use the animation
  481. /// duration of the previous track minus any mix duration plus the negative delay.</param>
  482. public TrackEntry AddEmptyAnimation (int trackIndex, float mixDuration, float delay) {
  483. if (delay <= 0) delay -= mixDuration;
  484. TrackEntry entry = AddAnimation(trackIndex, AnimationState.EmptyAnimation, false, delay);
  485. entry.mixDuration = mixDuration;
  486. entry.trackEnd = mixDuration;
  487. return entry;
  488. }
  489. /// <summary>
  490. /// Sets an empty animation for every track, discarding any queued animations, and mixes to it over the specified mix duration.</summary>
  491. public void SetEmptyAnimations (float mixDuration) {
  492. bool oldDrainDisabled = queue.drainDisabled;
  493. queue.drainDisabled = true;
  494. for (int i = 0, n = tracks.Count; i < n; i++) {
  495. TrackEntry current = tracks.Items[i];
  496. if (current != null) SetEmptyAnimation(i, mixDuration);
  497. }
  498. queue.drainDisabled = oldDrainDisabled;
  499. queue.Drain();
  500. }
  501. private TrackEntry ExpandToIndex (int index) {
  502. if (index < tracks.Count) return tracks.Items[index];
  503. while (index >= tracks.Count)
  504. tracks.Add(null);
  505. return null;
  506. }
  507. /// <summary>Object-pooling version of new TrackEntry. Obtain an unused TrackEntry from the pool and clear/initialize its values.</summary>
  508. /// <param name="last">May be null.</param>
  509. private TrackEntry NewTrackEntry (int trackIndex, Animation animation, bool loop, TrackEntry last) {
  510. TrackEntry entry = trackEntryPool.Obtain(); // Pooling
  511. entry.trackIndex = trackIndex;
  512. entry.animation = animation;
  513. entry.loop = loop;
  514. entry.eventThreshold = 0;
  515. entry.attachmentThreshold = 0;
  516. entry.drawOrderThreshold = 0;
  517. entry.animationStart = 0;
  518. entry.animationEnd = animation.Duration;
  519. entry.animationLast = -1;
  520. entry.nextAnimationLast = -1;
  521. entry.delay = 0;
  522. entry.trackTime = 0;
  523. entry.trackLast = -1;
  524. entry.nextTrackLast = -1; // nextTrackLast == -1 signifies a TrackEntry that wasn't applied yet.
  525. entry.trackEnd = float.MaxValue; // loop ? float.MaxValue : animation.Duration;
  526. entry.timeScale = 1;
  527. entry.alpha = 1;
  528. entry.interruptAlpha = 1;
  529. entry.mixTime = 0;
  530. entry.mixDuration = (last == null) ? 0 : data.GetMix(last.animation, animation);
  531. return entry;
  532. }
  533. /// <summary>Dispose all track entries queued after the given TrackEntry.</summary>
  534. private void DisposeNext (TrackEntry entry) {
  535. TrackEntry next = entry.next;
  536. while (next != null) {
  537. queue.Dispose(next);
  538. next = next.next;
  539. }
  540. entry.next = null;
  541. }
  542. private void AnimationsChanged () {
  543. animationsChanged = false;
  544. var propertyIDs = this.propertyIDs;
  545. propertyIDs.Clear();
  546. var mixingTo = this.mixingTo;
  547. var tracksItems = tracks.Items;
  548. for (int i = 0, n = tracks.Count; i < n; i++) {
  549. var entry = tracksItems[i];
  550. if (entry != null) entry.SetTimelineData(null, mixingTo, propertyIDs);
  551. }
  552. }
  553. /// <returns>The track entry for the animation currently playing on the track, or null if no animation is currently playing.</returns>
  554. public TrackEntry GetCurrent (int trackIndex) {
  555. return (trackIndex >= tracks.Count) ? null : tracks.Items[trackIndex];
  556. }
  557. override public string ToString () {
  558. var buffer = new System.Text.StringBuilder();
  559. for (int i = 0, n = tracks.Count; i < n; i++) {
  560. TrackEntry entry = tracks.Items[i];
  561. if (entry == null) continue;
  562. if (buffer.Length > 0) buffer.Append(", ");
  563. buffer.Append(entry.ToString());
  564. }
  565. return buffer.Length == 0 ? "<none>" : buffer.ToString();
  566. }
  567. internal void OnStart (TrackEntry entry) { if (Start != null) Start(entry); }
  568. internal void OnInterrupt (TrackEntry entry) { if (Interrupt != null) Interrupt(entry); }
  569. internal void OnEnd (TrackEntry entry) { if (End != null) End(entry); }
  570. internal void OnDispose (TrackEntry entry) { if (Dispose != null) Dispose(entry); }
  571. internal void OnComplete (TrackEntry entry) { if (Complete != null) Complete(entry); }
  572. internal void OnEvent (TrackEntry entry, Event e) { if (Event != null) Event(entry, e); }
  573. }
  574. /// <summary>State for the playback of an animation.</summary>
  575. public class TrackEntry : Pool<TrackEntry>.IPoolable {
  576. internal Animation animation;
  577. internal TrackEntry next, mixingFrom;
  578. internal int trackIndex;
  579. internal bool loop;
  580. internal float eventThreshold, attachmentThreshold, drawOrderThreshold;
  581. internal float animationStart, animationEnd, animationLast, nextAnimationLast;
  582. internal float delay, trackTime, trackLast, nextTrackLast, trackEnd, timeScale = 1f;
  583. internal float alpha, mixTime, mixDuration, interruptAlpha, totalAlpha;
  584. internal readonly ExposedList<int> timelineData = new ExposedList<int>();
  585. internal readonly ExposedList<TrackEntry> timelineDipMix = new ExposedList<TrackEntry>();
  586. internal readonly ExposedList<float> timelinesRotation = new ExposedList<float>();
  587. // IPoolable.Reset()
  588. public void Reset () {
  589. next = null;
  590. mixingFrom = null;
  591. animation = null;
  592. timelineData.Clear();
  593. timelineDipMix.Clear();
  594. timelinesRotation.Clear();
  595. Start = null;
  596. Interrupt = null;
  597. End = null;
  598. Dispose = null;
  599. Complete = null;
  600. Event = null;
  601. }
  602. /// <summary>Sets the timeline data.</summary>
  603. /// <param name="to">May be null.</param>
  604. internal TrackEntry SetTimelineData (TrackEntry to, ExposedList<TrackEntry> mixingToArray, HashSet<int> propertyIDs) {
  605. if (to != null) mixingToArray.Add(to);
  606. var lastEntry = mixingFrom != null ? mixingFrom.SetTimelineData(this, mixingToArray, propertyIDs) : this;
  607. if (to != null) mixingToArray.Pop();
  608. var mixingTo = mixingToArray.Items;
  609. int mixingToLast = mixingToArray.Count - 1;
  610. var timelines = animation.timelines.Items;
  611. int timelinesCount = animation.timelines.Count;
  612. var timelineDataItems = timelineData.Resize(timelinesCount).Items; // timelineData.setSize(timelinesCount);
  613. timelineDipMix.Clear();
  614. var timelineDipMixItems = timelineDipMix.Resize(timelinesCount).Items; //timelineDipMix.setSize(timelinesCount);
  615. // outer:
  616. for (int i = 0; i < timelinesCount; i++) {
  617. int id = timelines[i].PropertyId;
  618. if (!propertyIDs.Add(id)) {
  619. timelineDataItems[i] = AnimationState.Subsequent;
  620. } else if (to == null || !to.HasTimeline(id)) {
  621. timelineDataItems[i] = AnimationState.First;
  622. } else {
  623. for (int ii = mixingToLast; ii >= 0; ii--) {
  624. var entry = mixingTo[ii];
  625. if (!entry.HasTimeline(id)) {
  626. if (entry.mixDuration > 0) {
  627. timelineDataItems[i] = AnimationState.DipMix;
  628. timelineDipMixItems[i] = entry;
  629. goto continue_outer; // continue outer;
  630. }
  631. break;
  632. }
  633. }
  634. timelineDataItems[i] = AnimationState.Dip;
  635. }
  636. continue_outer: {}
  637. }
  638. return lastEntry;
  639. }
  640. bool HasTimeline (int id) {
  641. var timelines = animation.timelines.Items;
  642. for (int i = 0, n = animation.timelines.Count; i < n; i++)
  643. if (timelines[i].PropertyId == id) return true;
  644. return false;
  645. }
  646. /// <summary>The index of the track where this entry is either current or queued.</summary>
  647. public int TrackIndex { get { return trackIndex; } }
  648. /// <summary>The animation to apply for this track entry.</summary>
  649. public Animation Animation { get { return animation; } }
  650. /// <summary>
  651. /// If true, the animation will repeat. If false, it will not, instead its last frame is applied if played beyond its duration.</summary>
  652. public bool Loop { get { return loop; } set { loop = value; } }
  653. ///<summary>
  654. /// Seconds to postpone playing the animation. When a track entry is the current track entry, delay postpones incrementing
  655. /// the track time. When a track entry is queued, delay is the time from the start of the previous animation to when the
  656. /// track entry will become the current track entry.</summary>
  657. public float Delay { get { return delay; } set { delay = value; } }
  658. /// <summary>
  659. /// Current time in seconds this track entry has been the current track entry. The track time determines
  660. /// <see cref="TrackEntry.AnimationTime"/>. The track time can be set to start the animation at a time other than 0, without affecting looping.</summary>
  661. public float TrackTime { get { return trackTime; } set { trackTime = value; } }
  662. /// <summary>
  663. /// The track time in seconds when this animation will be removed from the track. Defaults to the animation duration for
  664. /// non-looping animations and to <see cref="int.MaxValue"/> for looping animations. If the track end time is reached and no
  665. /// other animations are queued for playback, and mixing from any previous animations is complete, properties keyed by the animation,
  666. /// are set to the setup pose and the track is cleared.
  667. ///
  668. /// It may be desired to use <see cref="AnimationState.AddEmptyAnimation(int, float, float)"/> to mix the properties back to the
  669. /// setup pose over time, rather than have it happen instantly.
  670. /// </summary>
  671. public float TrackEnd { get { return trackEnd; } set { trackEnd = value; } }
  672. /// <summary>
  673. /// Seconds when this animation starts, both initially and after looping. Defaults to 0.
  674. ///
  675. /// When changing the animation start time, it often makes sense to set <see cref="TrackEntry.AnimationLast"/> to the same value to
  676. /// prevent timeline keys before the start time from triggering.
  677. /// </summary>
  678. public float AnimationStart { get { return animationStart; } set { animationStart = value; } }
  679. /// <summary>
  680. /// Seconds for the last frame of this animation. Non-looping animations won't play past this time. Looping animations will
  681. /// loop back to <see cref="TrackEntry.AnimationStart"/> at this time. Defaults to the animation duration.</summary>
  682. public float AnimationEnd { get { return animationEnd; } set { animationEnd = value; } }
  683. /// <summary>
  684. /// The time in seconds this animation was last applied. Some timelines use this for one-time triggers. Eg, when this
  685. /// animation is applied, event timelines will fire all events between the animation last time (exclusive) and animation time
  686. /// (inclusive). Defaults to -1 to ensure triggers on frame 0 happen the first time this animation is applied.</summary>
  687. public float AnimationLast {
  688. get { return animationLast; }
  689. set {
  690. animationLast = value;
  691. nextAnimationLast = value;
  692. }
  693. }
  694. /// <summary>
  695. /// Uses <see cref="TrackEntry.TrackTime"/> to compute the animation time between <see cref="TrackEntry.AnimationStart"/>. and
  696. /// <see cref="TrackEntry.AnimationEnd"/>. When the track time is 0, the animation time is equal to the animation start time.
  697. /// </summary>
  698. public float AnimationTime {
  699. get {
  700. if (loop) {
  701. float duration = animationEnd - animationStart;
  702. if (duration == 0) return animationStart;
  703. return (trackTime % duration) + animationStart;
  704. }
  705. return Math.Min(trackTime + animationStart, animationEnd);
  706. }
  707. }
  708. /// <summary>
  709. /// Multiplier for the delta time when the animation state is updated, causing time for this animation to play slower or
  710. /// faster. Defaults to 1.
  711. /// </summary>
  712. public float TimeScale { get { return timeScale; } set { timeScale = value; } }
  713. /// <summary>
  714. /// Values less than 1 mix this animation with the last skeleton pose. Defaults to 1, which overwrites the last skeleton pose with
  715. /// this animation.
  716. ///
  717. /// Typically track 0 is used to completely pose the skeleton, then alpha can be used on higher tracks. It doesn't make sense
  718. /// to use alpha on track 0 if the skeleton pose is from the last frame render.
  719. /// </summary>
  720. public float Alpha { get { return alpha; } set { alpha = value; } }
  721. /// <summary>
  722. /// When the mix percentage (mix time / mix duration) is less than the event threshold, event timelines for the animation
  723. /// being mixed out will be applied. Defaults to 0, so event timelines are not applied for an animation being mixed out.</summary>
  724. public float EventThreshold { get { return eventThreshold; } set { eventThreshold = value; } }
  725. /// <summary>
  726. /// When the mix percentage (mix time / mix duration) is less than the attachment threshold, attachment timelines for the
  727. /// animation being mixed out will be applied. Defaults to 0, so attachment timelines are not applied for an animation being
  728. /// mixed out.</summary>
  729. public float AttachmentThreshold { get { return attachmentThreshold; } set { attachmentThreshold = value; } }
  730. /// <summary>
  731. /// When the mix percentage (mix time / mix duration) is less than the draw order threshold, draw order timelines for the
  732. /// animation being mixed out will be applied. Defaults to 0, so draw order timelines are not applied for an animation being
  733. /// mixed out.
  734. /// </summary>
  735. public float DrawOrderThreshold { get { return drawOrderThreshold; } set { drawOrderThreshold = value; } }
  736. /// <summary>
  737. /// The animation queued to start after this animation, or null.</summary>
  738. public TrackEntry Next { get { return next; } }
  739. /// <summary>
  740. /// Returns true if at least one loop has been completed.</summary>
  741. public bool IsComplete {
  742. get { return trackTime >= animationEnd - animationStart; }
  743. }
  744. /// <summary>
  745. /// Seconds from 0 to the mix duration when mixing from the previous animation to this animation. May be slightly more than
  746. /// <see cref="TrackEntry.MixDuration"/> when the mix is complete.</summary>
  747. public float MixTime { get { return mixTime; } set { mixTime = value; } }
  748. /// <summary>
  749. /// Seconds for mixing from the previous animation to this animation. Defaults to the value provided by
  750. /// <see cref="AnimationStateData"/> based on the animation before this animation (if any).
  751. ///
  752. /// The mix duration can be set manually rather than use the value from AnimationStateData.GetMix.
  753. /// In that case, the mixDuration must be set before <see cref="AnimationState.Update(float)"/> is next called.
  754. /// <para>
  755. /// When using <seealso cref="AnimationState.AddAnimation(int, Animation, bool, float)"/> with a
  756. /// <code>delay</code> less than or equal to 0, note the <seealso cref="Delay"/> is set using the mix duration from the <see cref=" AnimationStateData"/>
  757. /// </para>
  758. ///
  759. /// </summary>
  760. public float MixDuration { get { return mixDuration; } set { mixDuration = value; } }
  761. /// <summary>
  762. /// The track entry for the previous animation when mixing from the previous animation to this animation, or null if no
  763. /// mixing is currently occuring. When mixing from multiple animations, MixingFrom makes up a linked list.</summary>
  764. public TrackEntry MixingFrom { get { return mixingFrom; } }
  765. public event AnimationState.TrackEntryDelegate Start, Interrupt, End, Dispose, Complete;
  766. public event AnimationState.TrackEntryEventDelegate Event;
  767. internal void OnStart () { if (Start != null) Start(this); }
  768. internal void OnInterrupt () { if (Interrupt != null) Interrupt(this); }
  769. internal void OnEnd () { if (End != null) End(this); }
  770. internal void OnDispose () { if (Dispose != null) Dispose(this); }
  771. internal void OnComplete () { if (Complete != null) Complete(this); }
  772. internal void OnEvent (Event e) { if (Event != null) Event(this, e); }
  773. /// <summary>
  774. /// Resets the rotation directions for mixing this entry's rotate timelines. This can be useful to avoid bones rotating the
  775. /// long way around when using <see cref="alpha"/> and starting animations on other tracks.
  776. ///
  777. /// Mixing involves finding a rotation between two others, which has two possible solutions: the short way or the long way around.
  778. /// The two rotations likely change over time, so which direction is the short or long way also changes.
  779. /// If the short way was always chosen, bones would flip to the other side when that direction became the long way.
  780. /// TrackEntry chooses the short way the first time it is applied and remembers that direction.</summary>
  781. public void ResetRotationDirections () {
  782. timelinesRotation.Clear();
  783. }
  784. override public string ToString () {
  785. return animation == null ? "<none>" : animation.name;
  786. }
  787. }
  788. class EventQueue {
  789. private readonly List<EventQueueEntry> eventQueueEntries = new List<EventQueueEntry>();
  790. internal bool drainDisabled;
  791. private readonly AnimationState state;
  792. private readonly Pool<TrackEntry> trackEntryPool;
  793. internal event Action AnimationsChanged;
  794. internal EventQueue (AnimationState state, Action HandleAnimationsChanged, Pool<TrackEntry> trackEntryPool) {
  795. this.state = state;
  796. this.AnimationsChanged += HandleAnimationsChanged;
  797. this.trackEntryPool = trackEntryPool;
  798. }
  799. struct EventQueueEntry {
  800. public EventType type;
  801. public TrackEntry entry;
  802. public Event e;
  803. public EventQueueEntry (EventType eventType, TrackEntry trackEntry, Event e = null) {
  804. this.type = eventType;
  805. this.entry = trackEntry;
  806. this.e = e;
  807. }
  808. }
  809. enum EventType {
  810. Start, Interrupt, End, Dispose, Complete, Event
  811. }
  812. internal void Start (TrackEntry entry) {
  813. eventQueueEntries.Add(new EventQueueEntry(EventType.Start, entry));
  814. if (AnimationsChanged != null) AnimationsChanged();
  815. }
  816. internal void Interrupt (TrackEntry entry) {
  817. eventQueueEntries.Add(new EventQueueEntry(EventType.Interrupt, entry));
  818. }
  819. internal void End (TrackEntry entry) {
  820. eventQueueEntries.Add(new EventQueueEntry(EventType.End, entry));
  821. if (AnimationsChanged != null) AnimationsChanged();
  822. }
  823. internal void Dispose (TrackEntry entry) {
  824. eventQueueEntries.Add(new EventQueueEntry(EventType.Dispose, entry));
  825. }
  826. internal void Complete (TrackEntry entry) {
  827. eventQueueEntries.Add(new EventQueueEntry(EventType.Complete, entry));
  828. }
  829. internal void Event (TrackEntry entry, Event e) {
  830. eventQueueEntries.Add(new EventQueueEntry(EventType.Event, entry, e));
  831. }
  832. /// <summary>Raises all events in the queue and drains the queue.</summary>
  833. internal void Drain () {
  834. if (drainDisabled) return;
  835. drainDisabled = true;
  836. var entries = this.eventQueueEntries;
  837. AnimationState state = this.state;
  838. // Don't cache entries.Count so callbacks can queue their own events (eg, call SetAnimation in AnimationState_Complete).
  839. for (int i = 0; i < entries.Count; i++) {
  840. var queueEntry = entries[i];
  841. TrackEntry trackEntry = queueEntry.entry;
  842. switch (queueEntry.type) {
  843. case EventType.Start:
  844. trackEntry.OnStart();
  845. state.OnStart(trackEntry);
  846. break;
  847. case EventType.Interrupt:
  848. trackEntry.OnInterrupt();
  849. state.OnInterrupt(trackEntry);
  850. break;
  851. case EventType.End:
  852. trackEntry.OnEnd();
  853. state.OnEnd(trackEntry);
  854. goto case EventType.Dispose; // Fall through. (C#)
  855. case EventType.Dispose:
  856. trackEntry.OnDispose();
  857. state.OnDispose(trackEntry);
  858. trackEntryPool.Free(trackEntry); // Pooling
  859. break;
  860. case EventType.Complete:
  861. trackEntry.OnComplete();
  862. state.OnComplete(trackEntry);
  863. break;
  864. case EventType.Event:
  865. trackEntry.OnEvent(queueEntry.e);
  866. state.OnEvent(trackEntry, queueEntry.e);
  867. break;
  868. }
  869. }
  870. eventQueueEntries.Clear();
  871. drainDisabled = false;
  872. }
  873. internal void Clear () {
  874. eventQueueEntries.Clear();
  875. }
  876. }
  877. public class Pool<T> where T : class, new() {
  878. public readonly int max;
  879. readonly Stack<T> freeObjects;
  880. public int Count { get { return freeObjects.Count; } }
  881. public int Peak { get; private set; }
  882. public Pool (int initialCapacity = 16, int max = int.MaxValue) {
  883. freeObjects = new Stack<T>(initialCapacity);
  884. this.max = max;
  885. }
  886. public T Obtain () {
  887. return freeObjects.Count == 0 ? new T() : freeObjects.Pop();
  888. }
  889. public void Free (T obj) {
  890. if (obj == null) throw new ArgumentNullException("obj", "obj cannot be null");
  891. if (freeObjects.Count < max) {
  892. freeObjects.Push(obj);
  893. Peak = Math.Max(Peak, freeObjects.Count);
  894. }
  895. Reset(obj);
  896. }
  897. // protected void FreeAll (List<T> objects) {
  898. // if (objects == null) throw new ArgumentNullException("objects", "objects cannot be null.");
  899. // var freeObjects = this.freeObjects;
  900. // int max = this.max;
  901. // for (int i = 0; i < objects.Count; i++) {
  902. // T obj = objects[i];
  903. // if (obj == null) continue;
  904. // if (freeObjects.Count < max) freeObjects.Push(obj);
  905. // Reset(obj);
  906. // }
  907. // Peak = Math.Max(Peak, freeObjects.Count);
  908. // }
  909. public void Clear () {
  910. freeObjects.Clear();
  911. }
  912. protected void Reset (T obj) {
  913. var poolable = obj as IPoolable;
  914. if (poolable != null) poolable.Reset();
  915. }
  916. public interface IPoolable {
  917. void Reset ();
  918. }
  919. }
  920. }