AnimationState.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated January 1, 2020. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2020, Esoteric Software LLC
  6. *
  7. * Integration of the Spine Runtimes into software or otherwise creating
  8. * derivative works of the Spine Runtimes is permitted under the terms and
  9. * conditions of Section 2 of the Spine Editor License Agreement:
  10. * http://esotericsoftware.com/spine-editor-license
  11. *
  12. * Otherwise, it is permitted to integrate the Spine Runtimes into software
  13. * or otherwise create derivative works of the Spine Runtimes (collectively,
  14. * "Products"), provided that each user of the Products must obtain their own
  15. * Spine Editor license and redistribution of the Products in any form must
  16. * include this license and copyright notice.
  17. *
  18. * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
  24. * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27. * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. using System;
  30. using System.Collections.Generic;
  31. namespace Spine {
  32. /// <summary>
  33. /// <para>
  34. /// Applies animations over time, queues animations for later playback, mixes (crossfading) between animations, and applies
  35. /// multiple animations on top of each other (layering).</para>
  36. /// <para>
  37. /// See <a href='http://esotericsoftware.com/spine-applying-animations/'>Applying Animations</a> in the Spine Runtimes Guide.</para>
  38. /// </summary>
  39. public class AnimationState {
  40. internal static readonly Animation EmptyAnimation = new Animation("<empty>", new ExposedList<Timeline>(), 0);
  41. /// 1) A previously applied timeline has set this property.<para />
  42. /// Result: Mix from the current pose to the timeline pose.
  43. internal const int Subsequent = 0;
  44. /// 1) This is the first timeline to set this property.<para />
  45. /// 2) The next track entry applied after this one does not have a timeline to set this property.<para />
  46. /// Result: Mix from the setup pose to the timeline pose.
  47. internal const int First = 1;
  48. /// 1) A previously applied timeline has set this property.<br>
  49. /// 2) The next track entry to be applied does have a timeline to set this property.<br>
  50. /// 3) The next track entry after that one does not have a timeline to set this property.<br>
  51. /// Result: Mix from the current pose to the timeline pose, but do not mix out. This avoids "dipping" when crossfading
  52. /// animations that key the same property. A subsequent timeline will set this property using a mix.
  53. internal const int HoldSubsequent = 2;
  54. /// 1) This is the first timeline to set this property.<para />
  55. /// 2) The next track entry to be applied does have a timeline to set this property.<para />
  56. /// 3) The next track entry after that one does not have a timeline to set this property.<para />
  57. /// Result: Mix from the setup pose to the timeline pose, but do not mix out. This avoids "dipping" when crossfading animations
  58. /// that key the same property. A subsequent timeline will set this property using a mix.
  59. internal const int HoldFirst = 3;
  60. /// 1) This is the first timeline to set this property.<para />
  61. /// 2) The next track entry to be applied does have a timeline to set this property.<para />
  62. /// 3) The next track entry after that one does have a timeline to set this property.<para />
  63. /// 4) timelineHoldMix stores the first subsequent track entry that does not have a timeline to set this property.<para />
  64. /// Result: The same as HOLD except the mix percentage from the timelineHoldMix track entry is used. This handles when more than
  65. /// 2 track entries in a row have a timeline that sets the same property.<para />
  66. /// Eg, A -> B -> C -> D where A, B, and C have a timeline setting same property, but D does not. When A is applied, to avoid
  67. /// "dipping" A is not mixed out, however D (the first entry that doesn't set the property) mixing in is used to mix out A
  68. /// (which affects B and C). Without using D to mix out, A would be applied fully until mixing completes, then snap to the mixed
  69. /// out position.
  70. internal const int HoldMix = 4;
  71. internal const int Setup = 1, Current = 2;
  72. protected AnimationStateData data;
  73. private readonly ExposedList<TrackEntry> tracks = new ExposedList<TrackEntry>();
  74. private readonly ExposedList<Event> events = new ExposedList<Event>();
  75. // difference to libgdx reference: delegates are used for event callbacks instead of 'final SnapshotArray<AnimationStateListener> listeners'.
  76. internal void OnStart (TrackEntry entry) { if (Start != null) Start(entry); }
  77. internal void OnInterrupt (TrackEntry entry) { if (Interrupt != null) Interrupt(entry); }
  78. internal void OnEnd (TrackEntry entry) { if (End != null) End(entry); }
  79. internal void OnDispose (TrackEntry entry) { if (Dispose != null) Dispose(entry); }
  80. internal void OnComplete (TrackEntry entry) { if (Complete != null) Complete(entry); }
  81. internal void OnEvent (TrackEntry entry, Event e) { if (Event != null) Event(entry, e); }
  82. public delegate void TrackEntryDelegate (TrackEntry trackEntry);
  83. /// <summary>See <see href="http://esotericsoftware.com/spine-api-reference#AnimationStateListener-Methods">
  84. /// API Reference documentation pages here</see> for details. Usage in C# and spine-unity is explained
  85. /// <see href="http://esotericsoftware.com/spine-unity#Processing-AnimationState-Events">here</see>
  86. /// on the spine-unity documentation pages.</summary>
  87. public event TrackEntryDelegate Start, Interrupt, End, Dispose, Complete;
  88. public delegate void TrackEntryEventDelegate (TrackEntry trackEntry, Event e);
  89. public event TrackEntryEventDelegate Event;
  90. public void AssignEventSubscribersFrom (AnimationState src) {
  91. Event = src.Event;
  92. Start = src.Start;
  93. Interrupt = src.Interrupt;
  94. End = src.End;
  95. Dispose = src.Dispose;
  96. Complete = src.Complete;
  97. }
  98. public void AddEventSubscribersFrom (AnimationState src) {
  99. Event += src.Event;
  100. Start += src.Start;
  101. Interrupt += src.Interrupt;
  102. End += src.End;
  103. Dispose += src.Dispose;
  104. Complete += src.Complete;
  105. }
  106. // end of difference
  107. private readonly EventQueue queue; // Initialized by constructor.
  108. private readonly HashSet<string> propertyIds = new HashSet<string>();
  109. private bool animationsChanged;
  110. private float timeScale = 1;
  111. private int unkeyedState;
  112. private readonly Pool<TrackEntry> trackEntryPool = new Pool<TrackEntry>();
  113. public AnimationState (AnimationStateData data) {
  114. if (data == null) throw new ArgumentNullException("data", "data cannot be null.");
  115. this.data = data;
  116. this.queue = new EventQueue(
  117. this,
  118. delegate { this.animationsChanged = true; },
  119. trackEntryPool
  120. );
  121. }
  122. /// <summary>
  123. /// Increments the track entry <see cref="TrackEntry.TrackTime"/>, setting queued animations as current if needed.</summary>
  124. /// <param name="delta">delta time</param>
  125. public void Update (float delta) {
  126. delta *= timeScale;
  127. TrackEntry[] tracksItems = tracks.Items;
  128. for (int i = 0, n = tracks.Count; i < n; i++) {
  129. TrackEntry current = tracksItems[i];
  130. if (current == null) continue;
  131. current.animationLast = current.nextAnimationLast;
  132. current.trackLast = current.nextTrackLast;
  133. float currentDelta = delta * current.timeScale;
  134. if (current.delay > 0) {
  135. current.delay -= currentDelta;
  136. if (current.delay > 0) continue;
  137. currentDelta = -current.delay;
  138. current.delay = 0;
  139. }
  140. TrackEntry next = current.next;
  141. if (next != null) {
  142. // When the next entry's delay is passed, change to the next entry, preserving leftover time.
  143. float nextTime = current.trackLast - next.delay;
  144. if (nextTime >= 0) {
  145. next.delay = 0;
  146. next.trackTime += current.timeScale == 0 ? 0 : (nextTime / current.timeScale + delta) * next.timeScale;
  147. current.trackTime += currentDelta;
  148. SetCurrent(i, next, true);
  149. while (next.mixingFrom != null) {
  150. next.mixTime += delta;
  151. next = next.mixingFrom;
  152. }
  153. continue;
  154. }
  155. } else if (current.trackLast >= current.trackEnd && current.mixingFrom == null) {
  156. // Clear the track when there is no next entry, the track end time is reached, and there is no mixingFrom.
  157. tracksItems[i] = null;
  158. queue.End(current);
  159. ClearNext(current);
  160. continue;
  161. }
  162. if (current.mixingFrom != null && UpdateMixingFrom(current, delta)) {
  163. // End mixing from entries once all have completed.
  164. TrackEntry from = current.mixingFrom;
  165. current.mixingFrom = null;
  166. if (from != null) from.mixingTo = null;
  167. while (from != null) {
  168. queue.End(from);
  169. from = from.mixingFrom;
  170. }
  171. }
  172. current.trackTime += currentDelta;
  173. }
  174. queue.Drain();
  175. }
  176. /// <summary>Returns true when all mixing from entries are complete.</summary>
  177. private bool UpdateMixingFrom (TrackEntry to, float delta) {
  178. TrackEntry from = to.mixingFrom;
  179. if (from == null) return true;
  180. bool finished = UpdateMixingFrom(from, delta);
  181. from.animationLast = from.nextAnimationLast;
  182. from.trackLast = from.nextTrackLast;
  183. // Require mixTime > 0 to ensure the mixing from entry was applied at least once.
  184. if (to.mixTime > 0 && to.mixTime >= to.mixDuration) {
  185. // Require totalAlpha == 0 to ensure mixing is complete, unless mixDuration == 0 (the transition is a single frame).
  186. if (from.totalAlpha == 0 || to.mixDuration == 0) {
  187. to.mixingFrom = from.mixingFrom;
  188. if (from.mixingFrom != null) from.mixingFrom.mixingTo = to;
  189. to.interruptAlpha = from.interruptAlpha;
  190. queue.End(from);
  191. }
  192. return finished;
  193. }
  194. from.trackTime += delta * from.timeScale;
  195. to.mixTime += delta;
  196. return false;
  197. }
  198. /// <summary>
  199. /// Poses the skeleton using the track entry animations. The animation state is not changed, so can be applied to multiple
  200. /// skeletons to pose them identically.</summary>
  201. /// <returns>True if any animations were applied.</returns>
  202. public bool Apply (Skeleton skeleton) {
  203. if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null.");
  204. if (animationsChanged) AnimationsChanged();
  205. ExposedList<Event> events = this.events;
  206. bool applied = false;
  207. TrackEntry[] tracksItems = tracks.Items;
  208. for (int i = 0, n = tracks.Count; i < n; i++) {
  209. TrackEntry current = tracksItems[i];
  210. if (current == null || current.delay > 0) continue;
  211. applied = true;
  212. // Track 0 animations aren't for layering, so do not show the previously applied animations before the first key.
  213. MixBlend blend = i == 0 ? MixBlend.First : current.mixBlend;
  214. // Apply mixing from entries first.
  215. float mix = current.alpha;
  216. if (current.mixingFrom != null)
  217. mix *= ApplyMixingFrom(current, skeleton, blend);
  218. else if (current.trackTime >= current.trackEnd && current.next == null) //
  219. mix = 0; // Set to setup pose the last time the entry will be applied.
  220. // Apply current entry.
  221. float animationLast = current.animationLast, animationTime = current.AnimationTime, applyTime = animationTime;
  222. ExposedList<Event> applyEvents = events;
  223. if (current.reverse) {
  224. applyTime = current.animation.duration - applyTime;
  225. applyEvents = null;
  226. }
  227. int timelineCount = current.animation.timelines.Count;
  228. Timeline[] timelines = current.animation.timelines.Items;
  229. if ((i == 0 && mix == 1) || blend == MixBlend.Add) {
  230. for (int ii = 0; ii < timelineCount; ii++) {
  231. Timeline timeline = timelines[ii];
  232. if (timeline is AttachmentTimeline)
  233. ApplyAttachmentTimeline((AttachmentTimeline)timeline, skeleton, applyTime, blend, true);
  234. else
  235. timeline.Apply(skeleton, animationLast, applyTime, applyEvents, mix, blend, MixDirection.In);
  236. }
  237. } else {
  238. int[] timelineMode = current.timelineMode.Items;
  239. bool firstFrame = current.timelinesRotation.Count != timelineCount << 1;
  240. if (firstFrame) current.timelinesRotation.Resize(timelineCount << 1);
  241. float[] timelinesRotation = current.timelinesRotation.Items;
  242. for (int ii = 0; ii < timelineCount; ii++) {
  243. Timeline timeline = timelines[ii];
  244. MixBlend timelineBlend = timelineMode[ii] == AnimationState.Subsequent ? blend : MixBlend.Setup;
  245. var rotateTimeline = timeline as RotateTimeline;
  246. if (rotateTimeline != null)
  247. ApplyRotateTimeline(rotateTimeline, skeleton, applyTime, mix, timelineBlend, timelinesRotation,
  248. ii << 1, firstFrame);
  249. else if (timeline is AttachmentTimeline)
  250. ApplyAttachmentTimeline((AttachmentTimeline)timeline, skeleton, applyTime, blend, true);
  251. else
  252. timeline.Apply(skeleton, animationLast, applyTime, applyEvents, mix, timelineBlend, MixDirection.In);
  253. }
  254. }
  255. QueueEvents(current, animationTime);
  256. events.Clear(false);
  257. current.nextAnimationLast = animationTime;
  258. current.nextTrackLast = current.trackTime;
  259. }
  260. // Set slots attachments to the setup pose, if needed. This occurs if an animation that is mixing out sets attachments so
  261. // subsequent timelines see any deform, but the subsequent timelines don't set an attachment (eg they are also mixing out or
  262. // the time is before the first key).
  263. int setupState = unkeyedState + Setup;
  264. Slot[] slots = skeleton.slots.Items;
  265. for (int i = 0, n = skeleton.slots.Count; i < n; i++) {
  266. Slot slot = slots[i];
  267. if (slot.attachmentState == setupState) {
  268. string attachmentName = slot.data.attachmentName;
  269. slot.Attachment = (attachmentName == null ? null : skeleton.GetAttachment(slot.data.index, attachmentName));
  270. }
  271. }
  272. unkeyedState += 2; // Increasing after each use avoids the need to reset attachmentState for every slot.
  273. queue.Drain();
  274. return applied;
  275. }
  276. /// <summary>Version of <see cref="Apply"/> only applying and updating time at
  277. /// EventTimelines for lightweight off-screen updates.</summary>
  278. /// <param name="issueEvents">When set to false, only animation times of TrackEntries are updated.</param>
  279. // Note: This method is not part of the libgdx reference implementation.
  280. public bool ApplyEventTimelinesOnly (Skeleton skeleton, bool issueEvents = true) {
  281. if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null.");
  282. ExposedList<Event> events = this.events;
  283. bool applied = false;
  284. TrackEntry[] tracksItems = tracks.Items;
  285. for (int i = 0, n = tracks.Count; i < n; i++) {
  286. TrackEntry current = tracksItems[i];
  287. if (current == null || current.delay > 0) continue;
  288. applied = true;
  289. // Apply mixing from entries first.
  290. if (current.mixingFrom != null) ApplyMixingFromEventTimelinesOnly(current, skeleton, issueEvents);
  291. // Apply current entry.
  292. float animationLast = current.animationLast, animationTime = current.AnimationTime;
  293. if (issueEvents) {
  294. int timelineCount = current.animation.timelines.Count;
  295. Timeline[] timelines = current.animation.timelines.Items;
  296. for (int ii = 0; ii < timelineCount; ii++) {
  297. Timeline timeline = timelines[ii];
  298. if (timeline is EventTimeline)
  299. timeline.Apply(skeleton, animationLast, animationTime, events, 1.0f, MixBlend.Setup, MixDirection.In);
  300. }
  301. QueueEvents(current, animationTime);
  302. events.Clear(false);
  303. }
  304. current.nextAnimationLast = animationTime;
  305. current.nextTrackLast = current.trackTime;
  306. }
  307. if (issueEvents)
  308. queue.Drain();
  309. return applied;
  310. }
  311. private float ApplyMixingFrom (TrackEntry to, Skeleton skeleton, MixBlend blend) {
  312. TrackEntry from = to.mixingFrom;
  313. if (from.mixingFrom != null) ApplyMixingFrom(from, skeleton, blend);
  314. float mix;
  315. if (to.mixDuration == 0) { // Single frame mix to undo mixingFrom changes.
  316. mix = 1;
  317. if (blend == MixBlend.First) blend = MixBlend.Setup; // Tracks > 0 are transparent and can't reset to setup pose.
  318. } else {
  319. mix = to.mixTime / to.mixDuration;
  320. if (mix > 1) mix = 1;
  321. if (blend != MixBlend.First) blend = from.mixBlend; // Track 0 ignores track mix blend.
  322. }
  323. bool attachments = mix < from.attachmentThreshold, drawOrder = mix < from.drawOrderThreshold;
  324. int timelineCount = from.animation.timelines.Count;
  325. Timeline[] timelines = from.animation.timelines.Items;
  326. float alphaHold = from.alpha * to.interruptAlpha, alphaMix = alphaHold * (1 - mix);
  327. float animationLast = from.animationLast, animationTime = from.AnimationTime, applyTime = animationTime;
  328. ExposedList<Event> events = null;
  329. if (from.reverse)
  330. applyTime = from.animation.duration - applyTime;
  331. else {
  332. if (mix < from.eventThreshold) events = this.events;
  333. }
  334. if (blend == MixBlend.Add) {
  335. for (int i = 0; i < timelineCount; i++)
  336. timelines[i].Apply(skeleton, animationLast, applyTime, events, alphaMix, blend, MixDirection.Out);
  337. } else {
  338. int[] timelineMode = from.timelineMode.Items;
  339. TrackEntry[] timelineHoldMix = from.timelineHoldMix.Items;
  340. bool firstFrame = from.timelinesRotation.Count != timelineCount << 1;
  341. if (firstFrame) from.timelinesRotation.Resize(timelineCount << 1);
  342. float[] timelinesRotation = from.timelinesRotation.Items;
  343. from.totalAlpha = 0;
  344. for (int i = 0; i < timelineCount; i++) {
  345. Timeline timeline = timelines[i];
  346. MixDirection direction = MixDirection.Out;
  347. MixBlend timelineBlend;
  348. float alpha;
  349. switch (timelineMode[i]) {
  350. case AnimationState.Subsequent:
  351. if (!drawOrder && timeline is DrawOrderTimeline) continue;
  352. timelineBlend = blend;
  353. alpha = alphaMix;
  354. break;
  355. case AnimationState.First:
  356. timelineBlend = MixBlend.Setup;
  357. alpha = alphaMix;
  358. break;
  359. case AnimationState.HoldSubsequent:
  360. timelineBlend = blend;
  361. alpha = alphaHold;
  362. break;
  363. case AnimationState.HoldFirst:
  364. timelineBlend = MixBlend.Setup;
  365. alpha = alphaHold;
  366. break;
  367. default: // HoldMix
  368. timelineBlend = MixBlend.Setup;
  369. TrackEntry holdMix = timelineHoldMix[i];
  370. alpha = alphaHold * Math.Max(0, 1 - holdMix.mixTime / holdMix.mixDuration);
  371. break;
  372. }
  373. from.totalAlpha += alpha;
  374. var rotateTimeline = timeline as RotateTimeline;
  375. if (rotateTimeline != null) {
  376. ApplyRotateTimeline(rotateTimeline, skeleton, applyTime, alpha, timelineBlend, timelinesRotation, i << 1,
  377. firstFrame);
  378. } else if (timeline is AttachmentTimeline) {
  379. ApplyAttachmentTimeline((AttachmentTimeline)timeline, skeleton, applyTime, timelineBlend, attachments);
  380. } else {
  381. if (drawOrder && timeline is DrawOrderTimeline && timelineBlend == MixBlend.Setup)
  382. direction = MixDirection.In;
  383. timeline.Apply(skeleton, animationLast, applyTime, events, alpha, timelineBlend, direction);
  384. }
  385. }
  386. }
  387. if (to.mixDuration > 0) QueueEvents(from, animationTime);
  388. this.events.Clear(false);
  389. from.nextAnimationLast = animationTime;
  390. from.nextTrackLast = from.trackTime;
  391. return mix;
  392. }
  393. /// <summary>Version of <see cref="ApplyMixingFrom"/> only applying and updating time at
  394. /// EventTimelines for lightweight off-screen updates.</summary>
  395. /// <param name="issueEvents">When set to false, only animation times of TrackEntries are updated.</param>
  396. // Note: This method is not part of the libgdx reference implementation.
  397. private float ApplyMixingFromEventTimelinesOnly (TrackEntry to, Skeleton skeleton, bool issueEvents) {
  398. TrackEntry from = to.mixingFrom;
  399. if (from.mixingFrom != null) ApplyMixingFromEventTimelinesOnly(from, skeleton, issueEvents);
  400. float mix;
  401. if (to.mixDuration == 0) { // Single frame mix to undo mixingFrom changes.
  402. mix = 1;
  403. } else {
  404. mix = to.mixTime / to.mixDuration;
  405. if (mix > 1) mix = 1;
  406. }
  407. ExposedList<Event> eventBuffer = mix < from.eventThreshold ? this.events : null;
  408. if (eventBuffer == null) return mix;
  409. float animationLast = from.animationLast, animationTime = from.AnimationTime;
  410. if (issueEvents) {
  411. int timelineCount = from.animation.timelines.Count;
  412. Timeline[] timelines = from.animation.timelines.Items;
  413. for (int i = 0; i < timelineCount; i++) {
  414. Timeline timeline = timelines[i];
  415. if (timeline is EventTimeline)
  416. timeline.Apply(skeleton, animationLast, animationTime, eventBuffer, 0, MixBlend.Setup, MixDirection.Out);
  417. }
  418. if (to.mixDuration > 0) QueueEvents(from, animationTime);
  419. this.events.Clear(false);
  420. }
  421. from.nextAnimationLast = animationTime;
  422. from.nextTrackLast = from.trackTime;
  423. return mix;
  424. }
  425. /// <summary> Applies the attachment timeline and sets <see cref="Slot.attachmentState"/>.</summary>
  426. /// <param name="attachments">False when: 1) the attachment timeline is mixing out, 2) mix < attachmentThreshold, and 3) the timeline
  427. /// is not the last timeline to set the slot's attachment. In that case the timeline is applied only so subsequent
  428. /// timelines see any deform.</param>
  429. private void ApplyAttachmentTimeline (AttachmentTimeline timeline, Skeleton skeleton, float time, MixBlend blend,
  430. bool attachments) {
  431. Slot slot = skeleton.slots.Items[timeline.SlotIndex];
  432. if (!slot.bone.active) return;
  433. float[] frames = timeline.frames;
  434. if (time < frames[0]) { // Time is before first frame.
  435. if (blend == MixBlend.Setup || blend == MixBlend.First)
  436. SetAttachment(skeleton, slot, slot.data.attachmentName, attachments);
  437. } else
  438. SetAttachment(skeleton, slot, timeline.AttachmentNames[Timeline.Search(frames, time)], attachments);
  439. // If an attachment wasn't set (ie before the first frame or attachments is false), set the setup attachment later.
  440. if (slot.attachmentState <= unkeyedState) slot.attachmentState = unkeyedState + Setup;
  441. }
  442. private void SetAttachment (Skeleton skeleton, Slot slot, String attachmentName, bool attachments) {
  443. slot.Attachment = attachmentName == null ? null : skeleton.GetAttachment(slot.data.index, attachmentName);
  444. if (attachments) slot.attachmentState = unkeyedState + Current;
  445. }
  446. /// <summary>
  447. /// Applies the rotate timeline, mixing with the current pose while keeping the same rotation direction chosen as the shortest
  448. /// the first time the mixing was applied.</summary>
  449. static private void ApplyRotateTimeline (RotateTimeline timeline, Skeleton skeleton, float time, float alpha, MixBlend blend,
  450. float[] timelinesRotation, int i, bool firstFrame) {
  451. if (firstFrame) timelinesRotation[i] = 0;
  452. if (alpha == 1) {
  453. timeline.Apply(skeleton, 0, time, null, 1, blend, MixDirection.In);
  454. return;
  455. }
  456. Bone bone = skeleton.bones.Items[timeline.BoneIndex];
  457. if (!bone.active) return;
  458. float[] frames = timeline.frames;
  459. float r1, r2;
  460. if (time < frames[0]) { // Time is before first frame.
  461. switch (blend) {
  462. case MixBlend.Setup:
  463. bone.rotation = bone.data.rotation;
  464. goto default; // Fall through.
  465. default:
  466. return;
  467. case MixBlend.First:
  468. r1 = bone.rotation;
  469. r2 = bone.data.rotation;
  470. break;
  471. }
  472. } else {
  473. r1 = blend == MixBlend.Setup ? bone.data.rotation : bone.rotation;
  474. r2 = bone.data.rotation + timeline.GetCurveValue(time);
  475. }
  476. // Mix between rotations using the direction of the shortest route on the first frame.
  477. float total, diff = r2 - r1;
  478. diff -= (16384 - (int)(16384.499999999996 - diff / 360)) * 360;
  479. if (diff == 0) {
  480. total = timelinesRotation[i];
  481. } else {
  482. float lastTotal, lastDiff;
  483. if (firstFrame) {
  484. lastTotal = 0;
  485. lastDiff = diff;
  486. } else {
  487. lastTotal = timelinesRotation[i]; // Angle and direction of mix, including loops.
  488. lastDiff = timelinesRotation[i + 1]; // Difference between bones.
  489. }
  490. bool current = diff > 0, dir = lastTotal >= 0;
  491. // Detect cross at 0 (not 180).
  492. if (Math.Sign(lastDiff) != Math.Sign(diff) && Math.Abs(lastDiff) <= 90) {
  493. // A cross after a 360 rotation is a loop.
  494. if (Math.Abs(lastTotal) > 180) lastTotal += 360 * Math.Sign(lastTotal);
  495. dir = current;
  496. }
  497. total = diff + lastTotal - lastTotal % 360; // Store loops as part of lastTotal.
  498. if (dir != current) total += 360 * Math.Sign(lastTotal);
  499. timelinesRotation[i] = total;
  500. }
  501. timelinesRotation[i + 1] = diff;
  502. bone.rotation = r1 + total * alpha;
  503. }
  504. private void QueueEvents (TrackEntry entry, float animationTime) {
  505. float animationStart = entry.animationStart, animationEnd = entry.animationEnd;
  506. float duration = animationEnd - animationStart;
  507. float trackLastWrapped = entry.trackLast % duration;
  508. // Queue events before complete.
  509. Event[] eventsItems = this.events.Items;
  510. int i = 0, n = events.Count;
  511. for (; i < n; i++) {
  512. Event e = eventsItems[i];
  513. if (e.time < trackLastWrapped) break;
  514. if (e.time > animationEnd) continue; // Discard events outside animation start/end.
  515. queue.Event(entry, e);
  516. }
  517. // Queue complete if completed a loop iteration or the animation.
  518. bool complete = false;
  519. if (entry.loop)
  520. complete = duration == 0 || (trackLastWrapped > entry.trackTime % duration);
  521. else
  522. complete = animationTime >= animationEnd && entry.animationLast < animationEnd;
  523. if (complete) queue.Complete(entry);
  524. // Queue events after complete.
  525. for (; i < n; i++) {
  526. Event e = eventsItems[i];
  527. if (e.time < animationStart) continue; // Discard events outside animation start/end.
  528. queue.Event(entry, eventsItems[i]);
  529. }
  530. }
  531. /// <summary>
  532. /// <para>Removes all animations from all tracks, leaving skeletons in their current pose.</para>
  533. /// <para>
  534. /// It may be desired to use <see cref="AnimationState.SetEmptyAnimations(float)"/> to mix the skeletons back to the setup pose,
  535. /// rather than leaving them in their current pose.</para>
  536. /// </summary>
  537. public void ClearTracks () {
  538. bool oldDrainDisabled = queue.drainDisabled;
  539. queue.drainDisabled = true;
  540. for (int i = 0, n = tracks.Count; i < n; i++) {
  541. ClearTrack(i);
  542. }
  543. tracks.Clear();
  544. queue.drainDisabled = oldDrainDisabled;
  545. queue.Drain();
  546. }
  547. /// <summary>
  548. /// <para>Removes all animations from the track, leaving skeletons in their current pose.</para>
  549. /// <para>
  550. /// It may be desired to use <see cref="AnimationState.SetEmptyAnimation(int, float)"/> to mix the skeletons back to the setup pose,
  551. /// rather than leaving them in their current pose.</para>
  552. /// </summary>
  553. public void ClearTrack (int trackIndex) {
  554. if (trackIndex >= tracks.Count) return;
  555. TrackEntry current = tracks.Items[trackIndex];
  556. if (current == null) return;
  557. queue.End(current);
  558. ClearNext(current);
  559. TrackEntry entry = current;
  560. while (true) {
  561. TrackEntry from = entry.mixingFrom;
  562. if (from == null) break;
  563. queue.End(from);
  564. entry.mixingFrom = null;
  565. entry.mixingTo = null;
  566. entry = from;
  567. }
  568. tracks.Items[current.trackIndex] = null;
  569. queue.Drain();
  570. }
  571. /// <summary>Sets the active TrackEntry for a given track number.</summary>
  572. private void SetCurrent (int index, TrackEntry current, bool interrupt) {
  573. TrackEntry from = ExpandToIndex(index);
  574. tracks.Items[index] = current;
  575. current.previous = null;
  576. if (from != null) {
  577. if (interrupt) queue.Interrupt(from);
  578. current.mixingFrom = from;
  579. from.mixingTo = current;
  580. current.mixTime = 0;
  581. // Store the interrupted mix percentage.
  582. if (from.mixingFrom != null && from.mixDuration > 0)
  583. current.interruptAlpha *= Math.Min(1, from.mixTime / from.mixDuration);
  584. from.timelinesRotation.Clear(); // Reset rotation for mixing out, in case entry was mixed in.
  585. }
  586. queue.Start(current); // triggers AnimationsChanged
  587. }
  588. /// <summary>Sets an animation by name. <seealso cref="SetAnimation(int, Animation, bool)" /></summary>
  589. public TrackEntry SetAnimation (int trackIndex, string animationName, bool loop) {
  590. Animation animation = data.skeletonData.FindAnimation(animationName);
  591. if (animation == null) throw new ArgumentException("Animation not found: " + animationName, "animationName");
  592. return SetAnimation(trackIndex, animation, loop);
  593. }
  594. /// <summary>Sets the current animation for a track, discarding any queued animations. If the formerly current track entry was never
  595. /// applied to a skeleton, it is replaced (not mixed from).</summary>
  596. /// <param name="loop">If true, the animation will repeat. If false it will not, instead its last frame is applied if played beyond its
  597. /// duration. In either case<see cref="TrackEntry.TrackEnd"/> determines when the track is cleared.</param>
  598. /// <returns> A track entry to allow further customization of animation playback. References to the track entry must not be kept
  599. /// after the <see cref="AnimationState.Dispose"/> event occurs.</returns>
  600. public TrackEntry SetAnimation (int trackIndex, Animation animation, bool loop) {
  601. if (animation == null) throw new ArgumentNullException("animation", "animation cannot be null.");
  602. bool interrupt = true;
  603. TrackEntry current = ExpandToIndex(trackIndex);
  604. if (current != null) {
  605. if (current.nextTrackLast == -1) {
  606. // Don't mix from an entry that was never applied.
  607. tracks.Items[trackIndex] = current.mixingFrom;
  608. queue.Interrupt(current);
  609. queue.End(current);
  610. ClearNext(current);
  611. current = current.mixingFrom;
  612. interrupt = false; // mixingFrom is current again, but don't interrupt it twice.
  613. } else
  614. ClearNext(current);
  615. }
  616. TrackEntry entry = NewTrackEntry(trackIndex, animation, loop, current);
  617. SetCurrent(trackIndex, entry, interrupt);
  618. queue.Drain();
  619. return entry;
  620. }
  621. /// <summary>Queues an animation by name.</summary>
  622. /// <seealso cref="AddAnimation(int, Animation, bool, float)" />
  623. public TrackEntry AddAnimation (int trackIndex, string animationName, bool loop, float delay) {
  624. Animation animation = data.skeletonData.FindAnimation(animationName);
  625. if (animation == null) throw new ArgumentException("Animation not found: " + animationName, "animationName");
  626. return AddAnimation(trackIndex, animation, loop, delay);
  627. }
  628. /// <summary>Adds an animation to be played after the current or last queued animation for a track. If the track is empty, it is
  629. /// equivalent to calling <see cref="SetAnimation(int, Animation, bool)"/>.</summary>
  630. /// <param name="delay">
  631. /// If &gt; 0, sets <see cref="TrackEntry.Delay"/>. If &lt;= 0, the delay set is the duration of the previous track entry
  632. /// minus any mix duration (from the <see cref="AnimationStateData"/> plus the specified <code>Delay</code> (ie the mix
  633. /// ends at (<code>Delay</code> = 0) or before (<code>Delay</code> &lt; 0) the previous track entry duration). If the
  634. /// previous entry is looping, its next loop completion is used instead of its duration.
  635. /// </param>
  636. /// <returns>A track entry to allow further customization of animation playback. References to the track entry must not be kept
  637. /// after the <see cref="AnimationState.Dispose"/> event occurs.</returns>
  638. public TrackEntry AddAnimation (int trackIndex, Animation animation, bool loop, float delay) {
  639. if (animation == null) throw new ArgumentNullException("animation", "animation cannot be null.");
  640. TrackEntry last = ExpandToIndex(trackIndex);
  641. if (last != null) {
  642. while (last.next != null)
  643. last = last.next;
  644. }
  645. TrackEntry entry = NewTrackEntry(trackIndex, animation, loop, last);
  646. if (last == null) {
  647. SetCurrent(trackIndex, entry, true);
  648. queue.Drain();
  649. } else {
  650. last.next = entry;
  651. entry.previous = last;
  652. if (delay <= 0) delay += last.TrackComplete - entry.mixDuration;
  653. }
  654. entry.delay = delay;
  655. return entry;
  656. }
  657. /// <summary>
  658. /// <para>Sets an empty animation for a track, discarding any queued animations, and sets the track entry's
  659. /// <see cref="TrackEntry.getMixDuration()"/>. An empty animation has no timelines and serves as a placeholder for mixing in or out.</para>
  660. /// <para>
  661. /// Mixing out is done by setting an empty animation with a mix duration using either <see cref="AnimationState.SetEmptyAnimation(int, float)"/>,
  662. /// <see cref="AnimationState.SetEmptyAnimations(float)"/>, or <see cref="AnimationState.AddEmptyAnimation(int, float, float)"/>. Mixing to an empty animation causes
  663. /// the previous animation to be applied less and less over the mix duration. Properties keyed in the previous animation
  664. /// transition to the value from lower tracks or to the setup pose value if no lower tracks key the property. A mix duration of
  665. /// 0 still mixes out over one frame.</para>
  666. /// <para>
  667. /// Mixing in is done by first setting an empty animation, then adding an animation using
  668. /// <see cref="AnimationState.AddAnimation(int, Animation, bool, float)"/> with the desired delay (an empty animation has a duration of 0) and on
  669. /// the returned track entry, set the <see cref="TrackEntry.SetMixDuration(float)"/>. Mixing from an empty animation causes the new
  670. /// animation to be applied more and more over the mix duration. Properties keyed in the new animation transition from the value
  671. /// from lower tracks or from the setup pose value if no lower tracks key the property to the value keyed in the new
  672. /// animation.</para></summary>
  673. public TrackEntry SetEmptyAnimation (int trackIndex, float mixDuration) {
  674. TrackEntry entry = SetAnimation(trackIndex, AnimationState.EmptyAnimation, false);
  675. entry.mixDuration = mixDuration;
  676. entry.trackEnd = mixDuration;
  677. return entry;
  678. }
  679. /// <summary>
  680. /// Adds an empty animation to be played after the current or last queued animation for a track, and sets the track entry's
  681. /// <see cref="TrackEntry.MixDuration"/>. If the track is empty, it is equivalent to calling
  682. /// <see cref="AnimationState.SetEmptyAnimation(int, float)"/>.</summary>
  683. /// <seealso cref="AnimationState.SetEmptyAnimation(int, float)"/>
  684. /// <param name="trackIndex">Track number.</param>
  685. /// <param name="mixDuration">Mix duration.</param>
  686. /// <param name="delay">If &gt; 0, sets <see cref="TrackEntry.Delay"/>. If &lt;= 0, the delay set is the duration of the previous track entry
  687. /// minus any mix duration plus the specified <code>Delay</code> (ie the mix ends at (<code>Delay</code> = 0) or
  688. /// before (<code>Delay</code> &lt; 0) the previous track entry duration). If the previous entry is looping, its next
  689. /// loop completion is used instead of its duration.</param>
  690. /// <returns> A track entry to allow further customization of animation playback. References to the track entry must not be kept
  691. /// after the <see cref="AnimationState.Dispose"/> event occurs.
  692. /// </returns>
  693. public TrackEntry AddEmptyAnimation (int trackIndex, float mixDuration, float delay) {
  694. TrackEntry entry = AddAnimation(trackIndex, AnimationState.EmptyAnimation, false, delay);
  695. if (delay <= 0) entry.delay += entry.mixDuration - mixDuration;
  696. entry.mixDuration = mixDuration;
  697. entry.trackEnd = mixDuration;
  698. return entry;
  699. }
  700. /// <summary>
  701. /// Sets an empty animation for every track, discarding any queued animations, and mixes to it over the specified mix
  702. /// duration.</summary>
  703. public void SetEmptyAnimations (float mixDuration) {
  704. bool oldDrainDisabled = queue.drainDisabled;
  705. queue.drainDisabled = true;
  706. TrackEntry[] tracksItems = tracks.Items;
  707. for (int i = 0, n = tracks.Count; i < n; i++) {
  708. TrackEntry current = tracksItems[i];
  709. if (current != null) SetEmptyAnimation(current.trackIndex, mixDuration);
  710. }
  711. queue.drainDisabled = oldDrainDisabled;
  712. queue.Drain();
  713. }
  714. private TrackEntry ExpandToIndex (int index) {
  715. if (index < tracks.Count) return tracks.Items[index];
  716. tracks.Resize(index + 1);
  717. return null;
  718. }
  719. /// <summary>Object-pooling version of new TrackEntry. Obtain an unused TrackEntry from the pool and clear/initialize its values.</summary>
  720. /// <param name="last">May be null.</param>
  721. private TrackEntry NewTrackEntry (int trackIndex, Animation animation, bool loop, TrackEntry last) {
  722. TrackEntry entry = trackEntryPool.Obtain();
  723. entry.trackIndex = trackIndex;
  724. entry.animation = animation;
  725. entry.loop = loop;
  726. entry.holdPrevious = false;
  727. entry.eventThreshold = 0;
  728. entry.attachmentThreshold = 0;
  729. entry.drawOrderThreshold = 0;
  730. entry.animationStart = 0;
  731. entry.animationEnd = animation.Duration;
  732. entry.animationLast = -1;
  733. entry.nextAnimationLast = -1;
  734. entry.delay = 0;
  735. entry.trackTime = 0;
  736. entry.trackLast = -1;
  737. entry.nextTrackLast = -1;
  738. entry.trackEnd = float.MaxValue;
  739. entry.timeScale = 1;
  740. entry.alpha = 1;
  741. entry.interruptAlpha = 1;
  742. entry.mixTime = 0;
  743. entry.mixDuration = last == null ? 0 : data.GetMix(last.animation, animation);
  744. entry.mixBlend = MixBlend.Replace;
  745. return entry;
  746. }
  747. /// <summary>Removes the <see cref="TrackEntry.Next">next entry</see> and all entries after it for the specified entry.</summary>
  748. public void ClearNext (TrackEntry entry) {
  749. TrackEntry next = entry.next;
  750. while (next != null) {
  751. queue.Dispose(next);
  752. next = next.next;
  753. }
  754. entry.next = null;
  755. }
  756. private void AnimationsChanged () {
  757. animationsChanged = false;
  758. // Process in the order that animations are applied.
  759. propertyIds.Clear();
  760. int n = tracks.Count;
  761. TrackEntry[] tracksItems = tracks.Items;
  762. for (int i = 0; i < n; i++) {
  763. TrackEntry entry = tracksItems[i];
  764. if (entry == null) continue;
  765. while (entry.mixingFrom != null) // Move to last entry, then iterate in reverse.
  766. entry = entry.mixingFrom;
  767. do {
  768. if (entry.mixingTo == null || entry.mixBlend != MixBlend.Add) ComputeHold(entry);
  769. entry = entry.mixingTo;
  770. } while (entry != null);
  771. }
  772. }
  773. private void ComputeHold (TrackEntry entry) {
  774. TrackEntry to = entry.mixingTo;
  775. Timeline[] timelines = entry.animation.timelines.Items;
  776. int timelinesCount = entry.animation.timelines.Count;
  777. int[] timelineMode = entry.timelineMode.Resize(timelinesCount).Items;
  778. entry.timelineHoldMix.Clear();
  779. TrackEntry[] timelineHoldMix = entry.timelineHoldMix.Resize(timelinesCount).Items;
  780. HashSet<string> propertyIds = this.propertyIds;
  781. if (to != null && to.holdPrevious) {
  782. for (int i = 0; i < timelinesCount; i++)
  783. timelineMode[i] = propertyIds.AddAll(timelines[i].PropertyIds) ? AnimationState.HoldFirst : AnimationState.HoldSubsequent;
  784. return;
  785. }
  786. // outer:
  787. for (int i = 0; i < timelinesCount; i++) {
  788. Timeline timeline = timelines[i];
  789. String[] ids = timeline.PropertyIds;
  790. if (!propertyIds.AddAll(ids))
  791. timelineMode[i] = AnimationState.Subsequent;
  792. else if (to == null || timeline is AttachmentTimeline || timeline is DrawOrderTimeline
  793. || timeline is EventTimeline || !to.animation.HasTimeline(ids)) {
  794. timelineMode[i] = AnimationState.First;
  795. } else {
  796. for (TrackEntry next = to.mixingTo; next != null; next = next.mixingTo) {
  797. if (next.animation.HasTimeline(ids)) continue;
  798. if (next.mixDuration > 0) {
  799. timelineMode[i] = AnimationState.HoldMix;
  800. timelineHoldMix[i] = next;
  801. goto continue_outer; // continue outer;
  802. }
  803. break;
  804. }
  805. timelineMode[i] = AnimationState.HoldFirst;
  806. }
  807. continue_outer: { }
  808. }
  809. }
  810. /// <returns>The track entry for the animation currently playing on the track, or null if no animation is currently playing.</returns>
  811. public TrackEntry GetCurrent (int trackIndex) {
  812. if (trackIndex >= tracks.Count) return null;
  813. return tracks.Items[trackIndex];
  814. }
  815. /// <summary> Discards all listener notifications that have not yet been delivered. This can be useful to call from an
  816. /// AnimationState event subscriber when it is known that further notifications that may have been already queued for delivery
  817. /// are not wanted because new animations are being set.
  818. public void ClearListenerNotifications () {
  819. queue.Clear();
  820. }
  821. /// <summary>
  822. /// <para>Multiplier for the delta time when the animation state is updated, causing time for all animations and mixes to play slower
  823. /// or faster. Defaults to 1.</para>
  824. /// <para>
  825. /// See TrackEntry <see cref="TrackEntry.TimeScale"/> for affecting a single animation.</para>
  826. /// </summary>
  827. public float TimeScale { get { return timeScale; } set { timeScale = value; } }
  828. /// <summary>The AnimationStateData to look up mix durations.</summary>
  829. public AnimationStateData Data {
  830. get {
  831. return data;
  832. }
  833. set {
  834. if (data == null) throw new ArgumentNullException("data", "data cannot be null.");
  835. this.data = value;
  836. }
  837. }
  838. /// <summary>A list of tracks that have animations, which may contain nulls.</summary>
  839. public ExposedList<TrackEntry> Tracks { get { return tracks; } }
  840. override public string ToString () {
  841. var buffer = new System.Text.StringBuilder();
  842. TrackEntry[] tracksItems = tracks.Items;
  843. for (int i = 0, n = tracks.Count; i < n; i++) {
  844. TrackEntry entry = tracksItems[i];
  845. if (entry == null) continue;
  846. if (buffer.Length > 0) buffer.Append(", ");
  847. buffer.Append(entry.ToString());
  848. }
  849. if (buffer.Length == 0) return "<none>";
  850. return buffer.ToString();
  851. }
  852. }
  853. /// <summary>
  854. /// <para>
  855. /// Stores settings and other state for the playback of an animation on an <see cref="AnimationState"/> track.</para>
  856. /// <para>
  857. /// References to a track entry must not be kept after the <see cref="AnimationStateListener.Dispose(TrackEntry)"/> event occurs.</para>
  858. /// </summary>
  859. public class TrackEntry : Pool<TrackEntry>.IPoolable {
  860. internal Animation animation;
  861. internal TrackEntry previous, next, mixingFrom, mixingTo;
  862. // difference to libgdx reference: delegates are used for event callbacks instead of 'AnimationStateListener listener'.
  863. /// <summary>See <see href="http://esotericsoftware.com/spine-api-reference#AnimationStateListener-Methods">
  864. /// API Reference documentation pages here</see> for details. Usage in C# and spine-unity is explained
  865. /// <see href="http://esotericsoftware.com/spine-unity#Processing-AnimationState-Events">here</see>
  866. /// on the spine-unity documentation pages.</summary>
  867. public event AnimationState.TrackEntryDelegate Start, Interrupt, End, Dispose, Complete;
  868. public event AnimationState.TrackEntryEventDelegate Event;
  869. internal void OnStart () { if (Start != null) Start(this); }
  870. internal void OnInterrupt () { if (Interrupt != null) Interrupt(this); }
  871. internal void OnEnd () { if (End != null) End(this); }
  872. internal void OnDispose () { if (Dispose != null) Dispose(this); }
  873. internal void OnComplete () { if (Complete != null) Complete(this); }
  874. internal void OnEvent (Event e) { if (Event != null) Event(this, e); }
  875. internal int trackIndex;
  876. internal bool loop, holdPrevious, reverse;
  877. internal float eventThreshold, attachmentThreshold, drawOrderThreshold;
  878. internal float animationStart, animationEnd, animationLast, nextAnimationLast;
  879. internal float delay, trackTime, trackLast, nextTrackLast, trackEnd, timeScale = 1f;
  880. internal float alpha, mixTime, mixDuration, interruptAlpha, totalAlpha;
  881. internal MixBlend mixBlend = MixBlend.Replace;
  882. internal readonly ExposedList<int> timelineMode = new ExposedList<int>();
  883. internal readonly ExposedList<TrackEntry> timelineHoldMix = new ExposedList<TrackEntry>();
  884. internal readonly ExposedList<float> timelinesRotation = new ExposedList<float>();
  885. // IPoolable.Reset()
  886. public void Reset () {
  887. previous = null;
  888. next = null;
  889. mixingFrom = null;
  890. mixingTo = null;
  891. animation = null;
  892. // replaces 'listener = null;' since delegates are used for event callbacks
  893. Start = null;
  894. Interrupt = null;
  895. End = null;
  896. Dispose = null;
  897. Complete = null;
  898. Event = null;
  899. timelineMode.Clear();
  900. timelineHoldMix.Clear();
  901. timelinesRotation.Clear();
  902. }
  903. /// <summary>The index of the track where this entry is either current or queued.</summary>
  904. /// <seealso cref="AnimationState.GetCurrent(int)"/>
  905. public int TrackIndex { get { return trackIndex; } }
  906. /// <summary>The animation to apply for this track entry.</summary>
  907. public Animation Animation { get { return animation; } }
  908. /// <summary>
  909. /// If true, the animation will repeat. If false it will not, instead its last frame is applied if played beyond its
  910. /// duration.</summary>
  911. public bool Loop { get { return loop; } set { loop = value; } }
  912. ///<summary>
  913. /// <para>
  914. /// Seconds to postpone playing the animation. When this track entry is the current track entry, <code>Delay</code>
  915. /// postpones incrementing the <see cref="TrackEntry.TrackTime"/>. When this track entry is queued, <code>Delay</code> is the time from
  916. /// the start of the previous animation to when this track entry will become the current track entry (ie when the previous
  917. /// track entry <see cref="TrackEntry.TrackTime"/> &gt;= this track entry's <code>Delay</code>).</para>
  918. /// <para>
  919. /// <see cref="TrackEntry.TimeScale"/> affects the delay.</para>
  920. /// <para>
  921. /// When using <see cref="AnimationState.AddAnimation(int, Animation, bool, float)"/> with a <code>delay</code> <= 0, the delay
  922. /// is set using the mix duration from the <see cref="AnimationStateData"/>. If <see cref="mixDuration"/> is set afterward, the delay
  923. /// may need to be adjusted.</summary>
  924. public float Delay { get { return delay; } set { delay = value; } }
  925. /// <summary>
  926. /// Current time in seconds this track entry has been the current track entry. The track time determines
  927. /// <see cref="TrackEntry.AnimationTime"/>. The track time can be set to start the animation at a time other than 0, without affecting
  928. /// looping.</summary>
  929. public float TrackTime { get { return trackTime; } set { trackTime = value; } }
  930. /// <summary>
  931. /// <para>
  932. /// The track time in seconds when this animation will be removed from the track. Defaults to the highest possible float
  933. /// value, meaning the animation will be applied until a new animation is set or the track is cleared. If the track end time
  934. /// is reached, no other animations are queued for playback, and mixing from any previous animations is complete, then the
  935. /// properties keyed by the animation are set to the setup pose and the track is cleared.</para>
  936. /// <para>
  937. /// It may be desired to use <see cref="AnimationState.AddEmptyAnimation(int, float, float)"/> rather than have the animation
  938. /// abruptly cease being applied.</para>
  939. /// </summary>
  940. public float TrackEnd { get { return trackEnd; } set { trackEnd = value; } }
  941. /// <summary>
  942. /// If this track entry is non-looping, the track time in seconds when <see cref="AnimationEnd"/> is reached, or the current
  943. /// <see cref="TrackTime"/> if it has already been reached. If this track entry is looping, the track time when this
  944. /// animation will reach its next <see cref="AnimationEnd"/> (the next loop completion).</summary>
  945. public float TrackComplete {
  946. get {
  947. float duration = animationEnd - animationStart;
  948. if (duration != 0) {
  949. if (loop) return duration * (1 + (int)(trackTime / duration)); // Completion of next loop.
  950. if (trackTime < duration) return duration; // Before duration.
  951. }
  952. return trackTime; // Next update.
  953. }
  954. }
  955. /// <summary>
  956. /// <para>
  957. /// Seconds when this animation starts, both initially and after looping. Defaults to 0.</para>
  958. /// <para>
  959. /// When changing the <code>AnimationStart</code> time, it often makes sense to set <see cref="TrackEntry.AnimationLast"> to the same
  960. /// value to prevent timeline keys before the start time from triggering.</para>
  961. /// </summary>
  962. public float AnimationStart { get { return animationStart; } set { animationStart = value; } }
  963. /// <summary>
  964. /// Seconds for the last frame of this animation. Non-looping animations won't play past this time. Looping animations will
  965. /// loop back to <see cref="TrackEntry.AnimationStart"/> at this time. Defaults to the animation <see cref="Animation.Duration"/>.
  966. ///</summary>
  967. public float AnimationEnd { get { return animationEnd; } set { animationEnd = value; } }
  968. /// <summary>
  969. /// The time in seconds this animation was last applied. Some timelines use this for one-time triggers. Eg, when this
  970. /// animation is applied, event timelines will fire all events between the <code>AnimationLast</code> time (exclusive) and
  971. /// <code>AnimationTime</code> (inclusive). Defaults to -1 to ensure triggers on frame 0 happen the first time this animation
  972. /// is applied.</summary>
  973. public float AnimationLast {
  974. get { return animationLast; }
  975. set {
  976. animationLast = value;
  977. nextAnimationLast = value;
  978. }
  979. }
  980. /// <summary>
  981. /// Uses <see cref="TrackEntry.TrackTime"/> to compute the <code>AnimationTime</code>, which is between <see cref="TrackEntry.AnimationStart"/>
  982. /// and <see cref="TrackEntry.AnimationEnd"/>. When the <code>TrackTime</code> is 0, the <code>AnimationTime</code> is equal to the
  983. /// <code>AnimationStart</code> time.
  984. /// </summary>
  985. public float AnimationTime {
  986. get {
  987. if (loop) {
  988. float duration = animationEnd - animationStart;
  989. if (duration == 0) return animationStart;
  990. return (trackTime % duration) + animationStart;
  991. }
  992. return Math.Min(trackTime + animationStart, animationEnd);
  993. }
  994. }
  995. /// <summary>
  996. /// <para>
  997. /// Multiplier for the delta time when this track entry is updated, causing time for this animation to pass slower or
  998. /// faster. Defaults to 1.</para>
  999. /// <para>
  1000. /// Values < 0 are not supported. To play an animation in reverse, use <see cref="Reverse"/>.
  1001. /// <para>
  1002. /// <see cref="TrackEntry.MixTime"/> is not affected by track entry time scale, so <see cref="TrackEntry.MixDuration"/> may need to be adjusted to
  1003. /// match the animation speed.</para>
  1004. /// <para>
  1005. /// When using <see cref="AnimationState.AddAnimation(int, Animation, bool, float)"> with a <code>Delay</code> <= 0, the
  1006. /// <see cref="TrackEntry.Delay"/> is set using the mix duration from the <see cref="AnimationStateData"/>, assuming time scale to be 1. If
  1007. /// the time scale is not 1, the delay may need to be adjusted.</para>
  1008. /// <para>
  1009. /// See AnimationState <see cref="AnimationState.TimeScale"/> for affecting all animations.</para>
  1010. /// </summary>
  1011. public float TimeScale { get { return timeScale; } set { timeScale = value; } }
  1012. /// <summary>
  1013. /// <para>
  1014. /// Values < 1 mix this animation with the skeleton's current pose (usually the pose resulting from lower tracks). Defaults
  1015. /// to 1, which overwrites the skeleton's current pose with this animation.</para>
  1016. /// <para>
  1017. /// Typically track 0 is used to completely pose the skeleton, then alpha is used on higher tracks. It doesn't make sense to
  1018. /// use alpha on track 0 if the skeleton pose is from the last frame render.</para>
  1019. /// </summary>
  1020. public float Alpha { get { return alpha; } set { alpha = value; } }
  1021. public float InterruptAlpha { get { return interruptAlpha; } }
  1022. /// <summary>
  1023. /// When the mix percentage (<see cref="TrackEntry.MixTime"/> / <see cref="TrackEntry.MixDuration"/>) is less than the
  1024. /// <code>EventThreshold</code>, event timelines are applied while this animation is being mixed out. Defaults to 0, so event
  1025. /// timelines are not applied while this animation is being mixed out.
  1026. /// </summary>
  1027. public float EventThreshold { get { return eventThreshold; } set { eventThreshold = value; } }
  1028. /// <summary>
  1029. /// When the mix percentage (<see cref="TrackEntry.MixTime"/> / <see cref="TrackEntry.MixDuration"/>) is less than the
  1030. /// <code>AttachmentThreshold</code>, attachment timelines are applied while this animation is being mixed out. Defaults to
  1031. /// 0, so attachment timelines are not applied while this animation is being mixed out.
  1032. ///</summary>
  1033. public float AttachmentThreshold { get { return attachmentThreshold; } set { attachmentThreshold = value; } }
  1034. /// <summary>
  1035. /// When the mix percentage (<see cref="TrackEntry.MixTime"/> / <see cref="TrackEntry.MixDuration"/>) is less than the
  1036. /// <code>DrawOrderThreshold</code>, draw order timelines are applied while this animation is being mixed out. Defaults to 0,
  1037. /// so draw order timelines are not applied while this animation is being mixed out.
  1038. /// </summary>
  1039. public float DrawOrderThreshold { get { return drawOrderThreshold; } set { drawOrderThreshold = value; } }
  1040. /// <summary>
  1041. /// The animation queued to start after this animation, or null if there is none. <code>next</code> makes up a doubly linked
  1042. /// list.
  1043. /// <para>
  1044. /// See <see cref="AnimationState.ClearNext(TrackEntry)"/> to truncate the list.</para></summary>
  1045. public TrackEntry Next { get { return next; } }
  1046. /// <summary>
  1047. /// The animation queued to play before this animation, or null. <code>previous</code> makes up a doubly linked list.</summary>
  1048. public TrackEntry Previous { get { return previous; } }
  1049. /// <summary>
  1050. /// Returns true if at least one loop has been completed.</summary>
  1051. /// <seealso cref="TrackEntry.Complete"/>
  1052. public bool IsComplete {
  1053. get { return trackTime >= animationEnd - animationStart; }
  1054. }
  1055. /// <summary>
  1056. /// Seconds from 0 to the <see cref="TrackEntry.MixDuration"/> when mixing from the previous animation to this animation. May be
  1057. /// slightly more than <code>MixDuration</code> when the mix is complete.</summary>
  1058. public float MixTime { get { return mixTime; } set { mixTime = value; } }
  1059. /// <summary>
  1060. /// <para>
  1061. /// Seconds for mixing from the previous animation to this animation. Defaults to the value provided by AnimationStateData
  1062. /// <see cref="AnimationStateData.GetMix(Animation, Animation)"/> based on the animation before this animation (if any).</para>
  1063. /// <para>
  1064. /// The <code>MixDuration</code> can be set manually rather than use the value from
  1065. /// <see cref="AnimationStateData.GetMix(Animation, Animation)"/>. In that case, the <code>MixDuration</code> can be set for a new
  1066. /// track entry only before <see cref="AnimationState.Update(float)"/> is first called.</para>
  1067. /// <para>
  1068. /// When using <seealso cref="AnimationState.AddAnimation(int, Animation, bool, float)"/> with a <code>Delay</code> &lt;= 0, the
  1069. /// <see cref="TrackEntry.Delay"/> is set using the mix duration from the <see cref=" AnimationStateData"/>. If <code>mixDuration</code> is set
  1070. /// afterward, the delay may need to be adjusted. For example:
  1071. /// <code>entry.Delay = entry.previous.TrackComplete - entry.MixDuration;</code>
  1072. /// </para></summary>
  1073. public float MixDuration { get { return mixDuration; } set { mixDuration = value; } }
  1074. /// <summary>
  1075. /// <para>
  1076. /// Controls how properties keyed in the animation are mixed with lower tracks. Defaults to <see cref="MixBlend.Replace"/>.
  1077. /// </para><para>
  1078. /// Track entries on track 0 ignore this setting and always use <see cref="MixBlend.First"/>.
  1079. /// </para><para>
  1080. /// The <code>MixBlend</code> can be set for a new track entry only before <see cref="AnimationState.Apply(Skeleton)"/> is first
  1081. /// called.</para>
  1082. /// </summary>
  1083. public MixBlend MixBlend { get { return mixBlend; } set { mixBlend = value; } }
  1084. /// <summary>
  1085. /// The track entry for the previous animation when mixing from the previous animation to this animation, or null if no
  1086. /// mixing is currently occuring. When mixing from multiple animations, <code>MixingFrom</code> makes up a linked list.</summary>
  1087. public TrackEntry MixingFrom { get { return mixingFrom; } }
  1088. /// <summary>
  1089. /// The track entry for the next animation when mixing from this animation to the next animation, or null if no mixing is
  1090. /// currently occuring. When mixing to multiple animations, <code>MixingTo</code> makes up a linked list.</summary>
  1091. public TrackEntry MixingTo { get { return mixingTo; } }
  1092. /// <summary>
  1093. /// <para>
  1094. /// If true, when mixing from the previous animation to this animation, the previous animation is applied as normal instead
  1095. /// of being mixed out.</para>
  1096. /// <para>
  1097. /// When mixing between animations that key the same property, if a lower track also keys that property then the value will
  1098. /// briefly dip toward the lower track value during the mix. This happens because the first animation mixes from 100% to 0%
  1099. /// while the second animation mixes from 0% to 100%. Setting <code>HoldPrevious</code> to true applies the first animation
  1100. /// at 100% during the mix so the lower track value is overwritten. Such dipping does not occur on the lowest track which
  1101. /// keys the property, only when a higher track also keys the property.</para>
  1102. /// <para>
  1103. /// Snapping will occur if <code>HoldPrevious</code> is true and this animation does not key all the same properties as the
  1104. /// previous animation.</para>
  1105. /// </summary>
  1106. public bool HoldPrevious { get { return holdPrevious; } set { holdPrevious = value; } }
  1107. /// <summary>
  1108. /// If true, the animation will be applied in reverse. Events are not fired when an animation is applied in reverse.</summary>
  1109. public bool Reverse { get { return reverse; } set { reverse = value; } }
  1110. /// <summary>Returns true if this entry is for the empty animation. See <see cref="AnimationState.SetEmptyAnimation(int, float)"/>,
  1111. /// <see cref="AnimationState.AddEmptyAnimation(int, float, float)"/>, and <see cref="AnimationState.SetEmptyAnimations(float)"/>.
  1112. public bool IsEmptyAnimation { get { return animation == AnimationState.EmptyAnimation; } }
  1113. /// <summary>
  1114. /// <para>
  1115. /// Resets the rotation directions for mixing this entry's rotate timelines. This can be useful to avoid bones rotating the
  1116. /// long way around when using <see cref="alpha"/> and starting animations on other tracks.</para>
  1117. /// <para>
  1118. /// Mixing with <see cref="MixBlend.Replace"/> involves finding a rotation between two others, which has two possible solutions:
  1119. /// the short way or the long way around. The two rotations likely change over time, so which direction is the short or long
  1120. /// way also changes. If the short way was always chosen, bones would flip to the other side when that direction became the
  1121. /// long way. TrackEntry chooses the short way the first time it is applied and remembers that direction.</para>
  1122. /// </summary>
  1123. public void ResetRotationDirections () {
  1124. timelinesRotation.Clear();
  1125. }
  1126. override public string ToString () {
  1127. return animation == null ? "<none>" : animation.name;
  1128. }
  1129. // Note: This method is required by SpineAnimationStateMixerBehaviour,
  1130. // which is part of the timeline extension package. Thus the internal member variable
  1131. // nextTrackLast is not accessible. We favor providing this method
  1132. // over exposing nextTrackLast as public property, which would rather confuse users.
  1133. public void AllowImmediateQueue () {
  1134. if (nextTrackLast < 0) nextTrackLast = 0;
  1135. }
  1136. }
  1137. class EventQueue {
  1138. private readonly List<EventQueueEntry> eventQueueEntries = new List<EventQueueEntry>();
  1139. internal bool drainDisabled;
  1140. private readonly AnimationState state;
  1141. private readonly Pool<TrackEntry> trackEntryPool;
  1142. internal event Action AnimationsChanged;
  1143. internal EventQueue (AnimationState state, Action HandleAnimationsChanged, Pool<TrackEntry> trackEntryPool) {
  1144. this.state = state;
  1145. this.AnimationsChanged += HandleAnimationsChanged;
  1146. this.trackEntryPool = trackEntryPool;
  1147. }
  1148. internal void Start (TrackEntry entry) {
  1149. eventQueueEntries.Add(new EventQueueEntry(EventType.Start, entry));
  1150. if (AnimationsChanged != null) AnimationsChanged();
  1151. }
  1152. internal void Interrupt (TrackEntry entry) {
  1153. eventQueueEntries.Add(new EventQueueEntry(EventType.Interrupt, entry));
  1154. }
  1155. internal void End (TrackEntry entry) {
  1156. eventQueueEntries.Add(new EventQueueEntry(EventType.End, entry));
  1157. if (AnimationsChanged != null) AnimationsChanged();
  1158. }
  1159. internal void Dispose (TrackEntry entry) {
  1160. eventQueueEntries.Add(new EventQueueEntry(EventType.Dispose, entry));
  1161. }
  1162. internal void Complete (TrackEntry entry) {
  1163. eventQueueEntries.Add(new EventQueueEntry(EventType.Complete, entry));
  1164. }
  1165. internal void Event (TrackEntry entry, Event e) {
  1166. eventQueueEntries.Add(new EventQueueEntry(EventType.Event, entry, e));
  1167. }
  1168. /// <summary>Raises all events in the queue and drains the queue.</summary>
  1169. internal void Drain () {
  1170. if (drainDisabled) return;
  1171. drainDisabled = true;
  1172. List<EventQueueEntry> eventQueueEntries = this.eventQueueEntries;
  1173. AnimationState state = this.state;
  1174. // Don't cache eventQueueEntries.Count so callbacks can queue their own events (eg, call SetAnimation in AnimationState_Complete).
  1175. for (int i = 0; i < eventQueueEntries.Count; i++) {
  1176. EventQueueEntry queueEntry = eventQueueEntries[i];
  1177. TrackEntry trackEntry = queueEntry.entry;
  1178. switch (queueEntry.type) {
  1179. case EventType.Start:
  1180. trackEntry.OnStart();
  1181. state.OnStart(trackEntry);
  1182. break;
  1183. case EventType.Interrupt:
  1184. trackEntry.OnInterrupt();
  1185. state.OnInterrupt(trackEntry);
  1186. break;
  1187. case EventType.End:
  1188. trackEntry.OnEnd();
  1189. state.OnEnd(trackEntry);
  1190. goto case EventType.Dispose; // Fall through. (C#)
  1191. case EventType.Dispose:
  1192. trackEntry.OnDispose();
  1193. state.OnDispose(trackEntry);
  1194. trackEntryPool.Free(trackEntry);
  1195. break;
  1196. case EventType.Complete:
  1197. trackEntry.OnComplete();
  1198. state.OnComplete(trackEntry);
  1199. break;
  1200. case EventType.Event:
  1201. trackEntry.OnEvent(queueEntry.e);
  1202. state.OnEvent(trackEntry, queueEntry.e);
  1203. break;
  1204. }
  1205. }
  1206. eventQueueEntries.Clear();
  1207. drainDisabled = false;
  1208. }
  1209. internal void Clear () {
  1210. eventQueueEntries.Clear();
  1211. }
  1212. struct EventQueueEntry {
  1213. public EventType type;
  1214. public TrackEntry entry;
  1215. public Event e;
  1216. public EventQueueEntry (EventType eventType, TrackEntry trackEntry, Event e = null) {
  1217. this.type = eventType;
  1218. this.entry = trackEntry;
  1219. this.e = e;
  1220. }
  1221. }
  1222. enum EventType {
  1223. Start, Interrupt, End, Dispose, Complete, Event
  1224. }
  1225. }
  1226. class Pool<T> where T : class, new() {
  1227. public readonly int max;
  1228. readonly Stack<T> freeObjects;
  1229. public int Count { get { return freeObjects.Count; } }
  1230. public int Peak { get; private set; }
  1231. public Pool (int initialCapacity = 16, int max = int.MaxValue) {
  1232. freeObjects = new Stack<T>(initialCapacity);
  1233. this.max = max;
  1234. }
  1235. public T Obtain () {
  1236. return freeObjects.Count == 0 ? new T() : freeObjects.Pop();
  1237. }
  1238. public void Free (T obj) {
  1239. if (obj == null) throw new ArgumentNullException("obj", "obj cannot be null");
  1240. if (freeObjects.Count < max) {
  1241. freeObjects.Push(obj);
  1242. Peak = Math.Max(Peak, freeObjects.Count);
  1243. }
  1244. Reset(obj);
  1245. }
  1246. public void Clear () {
  1247. freeObjects.Clear();
  1248. }
  1249. protected void Reset (T obj) {
  1250. var poolable = obj as IPoolable;
  1251. if (poolable != null) poolable.Reset();
  1252. }
  1253. public interface IPoolable {
  1254. void Reset ();
  1255. }
  1256. }
  1257. public static class HashSetExtensions {
  1258. public static bool AddAll<T> (this HashSet<T> set, T[] addSet) {
  1259. bool anyItemAdded = false;
  1260. for (int i = 0, n = addSet.Length; i < n; ++i) {
  1261. T item = addSet[i];
  1262. anyItemAdded |= set.Add(item);
  1263. }
  1264. return anyItemAdded;
  1265. }
  1266. }
  1267. }