AnimationState.cs 56 KB

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