-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
AnimationState.java
1160 lines (997 loc) · 44.4 KB
/
AnimationState.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
package com.esotericsoftware.spine;
import static com.esotericsoftware.spine.Animation.RotateTimeline.*;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.BooleanArray;
import com.badlogic.gdx.utils.FloatArray;
import com.badlogic.gdx.utils.IntSet;
import com.badlogic.gdx.utils.Pool;
import com.badlogic.gdx.utils.Pool.Poolable;
import com.esotericsoftware.spine.Animation.AttachmentTimeline;
import com.esotericsoftware.spine.Animation.DrawOrderTimeline;
import com.esotericsoftware.spine.Animation.RotateTimeline;
import com.esotericsoftware.spine.Animation.Timeline;
/** Applies animations over time, queues animations for later playback, mixes (crossfading) between animations, and applies
* multiple animations on top of each other (layering).
* <p>
* See <a href='http://esotericsoftware.com/spine-applying-animations/'>Applying Animations</a> in the Spine Runtimes Guide. */
public class AnimationState {
static private final Animation emptyAnimation = new Animation("<empty>", new Array(0), 0);
private AnimationStateData data;
final Array<TrackEntry> tracks = new Array();
private final Array<Event> events = new Array();
final Array<AnimationStateListener> listeners = new Array();
private final EventQueue queue = new EventQueue();
private final IntSet propertyIDs = new IntSet();
boolean animationsChanged, multipleMixing;
private float timeScale = 1;
Pool<TrackEntry> trackEntryPool = new Pool() {
protected Object newObject () {
return new TrackEntry();
}
};
/** Creates an uninitialized AnimationState. The animation state data must be set before use. */
public AnimationState () {
}
public AnimationState (AnimationStateData data) {
if (data == null) throw new IllegalArgumentException("data cannot be null.");
this.data = data;
}
/** Increments each track entry {@link TrackEntry#getTrackTime()}, setting queued animations as current if needed. */
public void update (float delta) {
delta *= timeScale;
for (int i = 0, n = tracks.size; i < n; i++) {
TrackEntry current = tracks.get(i);
if (current == null) continue;
current.animationLast = current.nextAnimationLast;
current.trackLast = current.nextTrackLast;
float currentDelta = delta * current.timeScale;
if (current.delay > 0) {
current.delay -= currentDelta;
if (current.delay > 0) continue;
currentDelta = -current.delay;
current.delay = 0;
}
TrackEntry next = current.next;
if (next != null) {
// When the next entry's delay is passed, change to the next entry, preserving leftover time.
float nextTime = current.trackLast - next.delay;
if (nextTime >= 0) {
next.delay = 0;
next.trackTime = nextTime + delta * next.timeScale;
current.trackTime += currentDelta;
setCurrent(i, next, true);
while (next.mixingFrom != null) {
next.mixTime += currentDelta;
next = next.mixingFrom;
}
continue;
}
} else {
// Clear the track when there is no next entry, the track end time is reached, and there is no mixingFrom.
if (current.trackLast >= current.trackEnd && current.mixingFrom == null) {
tracks.set(i, null);
queue.end(current);
disposeNext(current);
continue;
}
}
updateMixingFrom(current, delta);
current.trackTime += currentDelta;
}
queue.drain();
}
private void updateMixingFrom (TrackEntry entry, float delta) {
TrackEntry from = entry.mixingFrom;
if (from == null) return;
updateMixingFrom(from, delta);
if (entry.mixTime >= entry.mixDuration && from.mixingFrom == null && entry.mixTime > 0) {
entry.mixingFrom = null;
queue.end(from);
return;
}
from.animationLast = from.nextAnimationLast;
from.trackLast = from.nextTrackLast;
from.trackTime += delta * from.timeScale;
entry.mixTime += delta * entry.timeScale;
}
/** Poses the skeleton using the track entry animations. There are no side effects other than invoking listeners, so the
* animation state can be applied to multiple skeletons to pose them identically. */
public void apply (Skeleton skeleton) {
if (skeleton == null) throw new IllegalArgumentException("skeleton cannot be null.");
if (animationsChanged) animationsChanged();
Array<Event> events = this.events;
for (int i = 0, n = tracks.size; i < n; i++) {
TrackEntry current = tracks.get(i);
if (current == null || current.delay > 0) continue;
// Apply mixing from entries first.
float mix = current.alpha;
if (current.mixingFrom != null)
mix *= applyMixingFrom(current, skeleton);
else if (current.trackTime >= current.trackEnd) //
mix = 0; // Set to setup pose the last time the entry will be applied.
// Apply current entry.
float animationLast = current.animationLast, animationTime = current.getAnimationTime();
int timelineCount = current.animation.timelines.size;
Object[] timelines = current.animation.timelines.items;
if (mix == 1) {
for (int ii = 0; ii < timelineCount; ii++)
((Timeline)timelines[ii]).apply(skeleton, animationLast, animationTime, events, 1, true, false);
} else {
boolean firstFrame = current.timelinesRotation.size == 0;
if (firstFrame) current.timelinesRotation.setSize(timelineCount << 1);
float[] timelinesRotation = current.timelinesRotation.items;
boolean[] timelinesFirst = current.timelinesFirst.items;
for (int ii = 0; ii < timelineCount; ii++) {
Timeline timeline = (Timeline)timelines[ii];
if (timeline instanceof RotateTimeline) {
applyRotateTimeline(timeline, skeleton, animationTime, mix, timelinesFirst[ii], timelinesRotation, ii << 1,
firstFrame);
} else
timeline.apply(skeleton, animationLast, animationTime, events, mix, timelinesFirst[ii], false);
}
}
queueEvents(current, animationTime);
events.clear();
current.nextAnimationLast = animationTime;
current.nextTrackLast = current.trackTime;
}
queue.drain();
}
private float applyMixingFrom (TrackEntry entry, Skeleton skeleton) {
TrackEntry from = entry.mixingFrom;
if (from.mixingFrom != null) applyMixingFrom(from, skeleton);
float mix;
if (entry.mixDuration == 0) // Single frame mix to undo mixingFrom changes.
mix = 1;
else {
mix = entry.mixTime / entry.mixDuration;
if (mix > 1) mix = 1;
}
Array<Event> events = mix < from.eventThreshold ? this.events : null;
boolean attachments = mix < from.attachmentThreshold, drawOrder = mix < from.drawOrderThreshold;
float animationLast = from.animationLast, animationTime = from.getAnimationTime();
int timelineCount = from.animation.timelines.size;
Object[] timelines = from.animation.timelines.items;
boolean[] timelinesFirst = from.timelinesFirst.items, timelinesLast = multipleMixing ? null : from.timelinesLast.items;
float alphaBase = from.alpha * entry.mixAlpha, alphaMix = alphaBase * (1 - mix);
boolean firstFrame = from.timelinesRotation.size == 0;
if (firstFrame) from.timelinesRotation.setSize(timelineCount << 1);
float[] timelinesRotation = from.timelinesRotation.items;
for (int i = 0; i < timelineCount; i++) {
Timeline timeline = (Timeline)timelines[i];
boolean setupPose = timelinesFirst[i];
float alpha = timelinesLast != null && setupPose && !timelinesLast[i] ? alphaBase : alphaMix;
if (timeline instanceof RotateTimeline)
applyRotateTimeline(timeline, skeleton, animationTime, alpha, setupPose, timelinesRotation, i << 1, firstFrame);
else {
if (!setupPose) {
if (!attachments && timeline instanceof AttachmentTimeline) continue;
if (!drawOrder && timeline instanceof DrawOrderTimeline) continue;
}
timeline.apply(skeleton, animationLast, animationTime, events, alpha, setupPose, true);
}
}
if (entry.mixDuration > 0) queueEvents(from, animationTime);
this.events.clear();
from.nextAnimationLast = animationTime;
from.nextTrackLast = from.trackTime;
return mix;
}
private void applyRotateTimeline (Timeline timeline, Skeleton skeleton, float time, float alpha, boolean setupPose,
float[] timelinesRotation, int i, boolean firstFrame) {
if (firstFrame) timelinesRotation[i] = 0;
if (alpha == 1) {
timeline.apply(skeleton, 0, time, null, 1, setupPose, false);
return;
}
RotateTimeline rotateTimeline = (RotateTimeline)timeline;
Bone bone = skeleton.bones.get(rotateTimeline.boneIndex);
float[] frames = rotateTimeline.frames;
if (time < frames[0]) { // Time is before first frame.
if (setupPose) bone.rotation = bone.data.rotation;
return;
}
float r2;
if (time >= frames[frames.length - ENTRIES]) // Time is after last frame.
r2 = bone.data.rotation + frames[frames.length + PREV_ROTATION];
else {
// Interpolate between the previous frame and the current frame.
int frame = Animation.binarySearch(frames, time, ENTRIES);
float prevRotation = frames[frame + PREV_ROTATION];
float frameTime = frames[frame];
float percent = rotateTimeline.getCurvePercent((frame >> 1) - 1,
1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime));
r2 = frames[frame + ROTATION] - prevRotation;
r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360;
r2 = prevRotation + r2 * percent + bone.data.rotation;
r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360;
}
// Mix between rotations using the direction of the shortest route on the first frame while detecting crosses.
float r1 = setupPose ? bone.data.rotation : bone.rotation;
float total, diff = r2 - r1;
if (diff == 0)
total = timelinesRotation[i];
else {
diff -= (16384 - (int)(16384.499999999996 - diff / 360)) * 360;
float lastTotal, lastDiff;
if (firstFrame) {
lastTotal = 0;
lastDiff = diff;
} else {
lastTotal = timelinesRotation[i]; // Angle and direction of mix, including loops.
lastDiff = timelinesRotation[i + 1]; // Difference between bones.
}
boolean current = diff > 0, dir = lastTotal >= 0;
// Detect cross at 0 (not 180).
if (Math.signum(lastDiff) != Math.signum(diff) && Math.abs(lastDiff) <= 90) {
// A cross after a 360 rotation is a loop.
if (Math.abs(lastTotal) > 180) lastTotal += 360 * Math.signum(lastTotal);
dir = current;
}
total = diff + lastTotal - lastTotal % 360; // Store loops as part of lastTotal.
if (dir != current) total += 360 * Math.signum(lastTotal);
timelinesRotation[i] = total;
}
timelinesRotation[i + 1] = diff;
r1 += total * alpha;
bone.rotation = r1 - (16384 - (int)(16384.499999999996 - r1 / 360)) * 360;
}
private void queueEvents (TrackEntry entry, float animationTime) {
float animationStart = entry.animationStart, animationEnd = entry.animationEnd;
float duration = animationEnd - animationStart;
float trackLastWrapped = entry.trackLast % duration;
// Queue events before complete.
Array<Event> events = this.events;
int i = 0, n = events.size;
for (; i < n; i++) {
Event event = events.get(i);
if (event.time < trackLastWrapped) break;
if (event.time > animationEnd) continue; // Discard events outside animation start/end.
queue.event(entry, event);
}
// Queue complete if completed a loop iteration or the animation.
if (entry.loop ? (trackLastWrapped > entry.trackTime % duration)
: (animationTime >= animationEnd && entry.animationLast < animationEnd)) {
queue.complete(entry);
}
// Queue events after complete.
for (; i < n; i++) {
Event event = events.get(i);
if (event.time < animationStart) continue; // Discard events outside animation start/end.
queue.event(entry, events.get(i));
}
}
/** Removes all animations from all tracks, leaving skeletons in their previous pose.
* <p>
* It may be desired to use {@link AnimationState#setEmptyAnimations(float)} to mix the skeletons back to the setup pose,
* rather than leaving them in their previous pose. */
public void clearTracks () {
boolean oldDrainDisabled = queue.drainDisabled;
queue.drainDisabled = true;
for (int i = 0, n = tracks.size; i < n; i++)
clearTrack(i);
tracks.clear();
queue.drainDisabled = oldDrainDisabled;
queue.drain();
}
/** Removes all animations from the track, leaving skeletons in their previous pose.
* <p>
* It may be desired to use {@link AnimationState#setEmptyAnimation(int, float)} to mix the skeletons back to the setup pose,
* rather than leaving them in their previous pose. */
public void clearTrack (int trackIndex) {
if (trackIndex >= tracks.size) return;
TrackEntry current = tracks.get(trackIndex);
if (current == null) return;
queue.end(current);
disposeNext(current);
TrackEntry entry = current;
while (true) {
TrackEntry from = entry.mixingFrom;
if (from == null) break;
queue.end(from);
entry.mixingFrom = null;
entry = from;
}
tracks.set(current.trackIndex, null);
queue.drain();
}
private void setCurrent (int index, TrackEntry current, boolean interrupt) {
TrackEntry from = expandToIndex(index);
tracks.set(index, current);
if (from != null) {
if (interrupt) queue.interrupt(from);
current.mixingFrom = from;
current.mixTime = 0;
TrackEntry mixingFrom = from.mixingFrom;
if (mixingFrom != null && from.mixDuration > 0) {
if (multipleMixing) {
// The interrupted mix will mix out from its current percentage to zero.
current.mixAlpha *= Math.min(from.mixTime / from.mixDuration, 1);
} else {
// A mix was interrupted, mix from the closest animation.
if (from.mixTime / from.mixDuration < 0.5f && mixingFrom.animation != emptyAnimation) {
current.mixingFrom = mixingFrom;
mixingFrom.mixingFrom = from;
mixingFrom.mixTime = from.mixDuration - from.mixTime;
mixingFrom.mixDuration = from.mixDuration;
from.mixingFrom = null;
from = mixingFrom;
}
// End the other animation after it is applied one last time.
from.mixAlpha = 0;
from.mixTime = 0;
from.mixDuration = 0;
}
}
from.timelinesRotation.clear(); // Reset rotation for mixing out, in case entry was mixed in.
}
queue.start(current);
}
/** Sets an animation by name.
* <p>
* {@link #setAnimation(int, Animation, boolean)}. */
public TrackEntry setAnimation (int trackIndex, String animationName, boolean loop) {
Animation animation = data.skeletonData.findAnimation(animationName);
if (animation == null) throw new IllegalArgumentException("Animation not found: " + animationName);
return setAnimation(trackIndex, animation, loop);
}
/** Sets the current animation for a track, discarding any queued animations.
* @param loop If true, the animation will repeat. If false it will not, instead its last frame is applied if played beyond its
* duration. In either case {@link TrackEntry#getTrackEnd()} determines when the track is cleared.
* @return A track entry to allow further customization of animation playback. References to the track entry must not be kept
* after the {@link AnimationStateListener#dispose(TrackEntry)} event occurs. */
public TrackEntry setAnimation (int trackIndex, Animation animation, boolean loop) {
if (animation == null) throw new IllegalArgumentException("animation cannot be null.");
boolean interrupt = true;
TrackEntry current = expandToIndex(trackIndex);
if (current != null) {
if (current.nextTrackLast == -1) {
// Don't mix from an entry that was never applied.
tracks.set(trackIndex, current.mixingFrom);
queue.interrupt(current);
queue.end(current);
disposeNext(current);
current = current.mixingFrom;
interrupt = false; // mixingFrom is current again, but don't interrupt it twice.
} else
disposeNext(current);
}
TrackEntry entry = trackEntry(trackIndex, animation, loop, current);
setCurrent(trackIndex, entry, interrupt);
queue.drain();
return entry;
}
/** Queues an animation by name.
* <p>
* See {@link #addAnimation(int, Animation, boolean, float)}. */
public TrackEntry addAnimation (int trackIndex, String animationName, boolean loop, float delay) {
Animation animation = data.skeletonData.findAnimation(animationName);
if (animation == null) throw new IllegalArgumentException("Animation not found: " + animationName);
return addAnimation(trackIndex, animation, loop, delay);
}
/** Adds an animation to be played after the current or last queued animation for a track. If the track is empty, it is
* equivalent to calling {@link #setAnimation(int, Animation, boolean)}.
* @param delay Seconds to begin this animation after the start of the previous animation. May be <= 0 to use the animation
* duration of the previous track minus any mix duration plus the <code>delay</code>.
* @return A track entry to allow further customization of animation playback. References to the track entry must not be kept
* after the {@link AnimationStateListener#dispose(TrackEntry)} event occurs. */
public TrackEntry addAnimation (int trackIndex, Animation animation, boolean loop, float delay) {
if (animation == null) throw new IllegalArgumentException("animation cannot be null.");
TrackEntry last = expandToIndex(trackIndex);
if (last != null) {
while (last.next != null)
last = last.next;
}
TrackEntry entry = trackEntry(trackIndex, animation, loop, last);
if (last == null) {
setCurrent(trackIndex, entry, true);
queue.drain();
} else {
last.next = entry;
if (delay <= 0) {
float duration = last.animationEnd - last.animationStart;
if (duration != 0)
delay += duration * (1 + (int)(last.trackTime / duration)) - data.getMix(last.animation, animation);
else
delay = 0;
}
}
entry.delay = delay;
return entry;
}
/** Sets an empty animation for a track, discarding any queued animations, and sets the track entry's
* {@link TrackEntry#getMixDuration()}.
* <p>
* Mixing out is done by setting an empty animation. A mix duration of 0 still mixes out over one frame.
* <p>
* To mix in, first set an empty animation and add an animation using {@link #addAnimation(int, Animation, boolean, float)},
* then set the {@link TrackEntry#setMixDuration(float)} on the returned track entry. */
public TrackEntry setEmptyAnimation (int trackIndex, float mixDuration) {
TrackEntry entry = setAnimation(trackIndex, emptyAnimation, false);
entry.mixDuration = mixDuration;
entry.trackEnd = mixDuration;
return entry;
}
/** Adds an empty animation to be played after the current or last queued animation for a track, and sets the track entry's
* {@link TrackEntry#getMixDuration()}. If the track is empty, it is equivalent to calling
* {@link #setEmptyAnimation(int, float)}.
* @param delay Seconds to begin this animation after the start of the previous animation. May be <= 0 to use the animation
* duration of the previous track minus any mix duration plus <code>delay</code>.
* @return A track entry to allow further customization of animation playback. References to the track entry must not be kept
* after the {@link AnimationStateListener#dispose(TrackEntry)} event occurs. */
public TrackEntry addEmptyAnimation (int trackIndex, float mixDuration, float delay) {
if (delay <= 0) delay -= mixDuration;
TrackEntry entry = addAnimation(trackIndex, emptyAnimation, false, delay);
entry.mixDuration = mixDuration;
entry.trackEnd = mixDuration;
return entry;
}
/** Sets an empty animation for every track, discarding any queued animations, and mixes to it over the specified mix
* duration. */
public void setEmptyAnimations (float mixDuration) {
boolean oldDrainDisabled = queue.drainDisabled;
queue.drainDisabled = true;
for (int i = 0, n = tracks.size; i < n; i++) {
TrackEntry current = tracks.get(i);
if (current != null) setEmptyAnimation(current.trackIndex, mixDuration);
}
queue.drainDisabled = oldDrainDisabled;
queue.drain();
}
private TrackEntry expandToIndex (int index) {
if (index < tracks.size) return tracks.get(index);
tracks.ensureCapacity(index - tracks.size + 1);
tracks.size = index + 1;
return null;
}
/** @param last May be null. */
private TrackEntry trackEntry (int trackIndex, Animation animation, boolean loop, TrackEntry last) {
TrackEntry entry = trackEntryPool.obtain();
entry.trackIndex = trackIndex;
entry.animation = animation;
entry.loop = loop;
entry.eventThreshold = 0;
entry.attachmentThreshold = 0;
entry.drawOrderThreshold = 0;
entry.animationStart = 0;
entry.animationEnd = animation.getDuration();
entry.animationLast = -1;
entry.nextAnimationLast = -1;
entry.delay = 0;
entry.trackTime = 0;
entry.trackLast = -1;
entry.nextTrackLast = -1;
entry.trackEnd = Float.MAX_VALUE;
entry.timeScale = 1;
entry.alpha = 1;
entry.mixAlpha = 1;
entry.mixTime = 0;
entry.mixDuration = last == null ? 0 : data.getMix(last.animation, animation);
return entry;
}
private void disposeNext (TrackEntry entry) {
TrackEntry next = entry.next;
while (next != null) {
queue.dispose(next);
next = next.next;
}
entry.next = null;
}
private void animationsChanged () {
animationsChanged = false;
IntSet propertyIDs = this.propertyIDs;
// Set timelinesFirst for all entries, from lowest track to highest.
int i = 0, n = tracks.size;
propertyIDs.clear();
for (; i < n; i++) { // Find first non-null entry.
TrackEntry entry = tracks.get(i);
if (entry == null) continue;
setTimelinesFirst(entry);
i++;
break;
}
for (; i < n; i++) { // Rest of entries.
TrackEntry entry = tracks.get(i);
if (entry != null) checkTimelinesFirst(entry);
}
if (multipleMixing) return;
// Set timelinesLast for mixingFrom entries, from highest track to lowest that has mixingFrom.
propertyIDs.clear();
int lowestMixingFrom = n;
for (i = 0; i < n; i++) { // Find lowest track with a mixingFrom entry.
TrackEntry entry = tracks.get(i);
if (entry == null || entry.mixingFrom == null) continue;
lowestMixingFrom = i;
break;
}
for (i = n - 1; i >= lowestMixingFrom; i--) { // Find first non-null entry.
TrackEntry entry = tracks.get(i);
if (entry == null) continue;
// Store properties for non-mixingFrom entry but don't set timelinesLast, which is only used for mixingFrom entries.
Object[] timelines = entry.animation.timelines.items;
for (int ii = 0, nn = entry.animation.timelines.size; ii < nn; ii++)
propertyIDs.add(((Timeline)timelines[ii]).getPropertyId());
entry = entry.mixingFrom;
while (entry != null) {
checkTimelinesUsage(entry, entry.timelinesLast);
entry = entry.mixingFrom;
}
}
}
/** From last to first mixingFrom entries, sets timelinesFirst to true on last, calls checkTimelineUsage on rest. */
private void setTimelinesFirst (TrackEntry entry) {
if (entry.mixingFrom != null) {
setTimelinesFirst(entry.mixingFrom);
checkTimelinesUsage(entry, entry.timelinesFirst);
return;
}
IntSet propertyIDs = this.propertyIDs;
int n = entry.animation.timelines.size;
Object[] timelines = entry.animation.timelines.items;
boolean[] usage = entry.timelinesFirst.setSize(n);
for (int i = 0; i < n; i++) {
propertyIDs.add(((Timeline)timelines[i]).getPropertyId());
usage[i] = true;
}
}
/** From last to first mixingFrom entries, calls checkTimelineUsage. */
private void checkTimelinesFirst (TrackEntry entry) {
if (entry.mixingFrom != null) checkTimelinesFirst(entry.mixingFrom);
checkTimelinesUsage(entry, entry.timelinesFirst);
}
private void checkTimelinesUsage (TrackEntry entry, BooleanArray usageArray) {
IntSet propertyIDs = this.propertyIDs;
int n = entry.animation.timelines.size;
Object[] timelines = entry.animation.timelines.items;
boolean[] usage = usageArray.setSize(n);
for (int i = 0; i < n; i++)
usage[i] = propertyIDs.add(((Timeline)timelines[i]).getPropertyId());
}
/** Returns the track entry for the animation currently playing on the track, or null if no animation is currently playing. */
public TrackEntry getCurrent (int trackIndex) {
if (trackIndex >= tracks.size) return null;
return tracks.get(trackIndex);
}
/** Adds a listener to receive events for all track entries. */
public void addListener (AnimationStateListener listener) {
if (listener == null) throw new IllegalArgumentException("listener cannot be null.");
listeners.add(listener);
}
/** Removes the listener added with {@link #addListener(AnimationStateListener)}. */
public void removeListener (AnimationStateListener listener) {
listeners.removeValue(listener, true);
}
/** Removes all listeners added with {@link #addListener(AnimationStateListener)}. */
public void clearListeners () {
listeners.clear();
}
/** Discards all listener notifications that have not yet been delivered. This can be useful to call from an
* {@link AnimationStateListener} when it is known that further notifications that may have been already queued for delivery
* are not wanted because new animations are being set. */
public void clearListenerNotifications () {
queue.clear();
}
/** Multiplier for the delta time when the animation state is updated, causing time for all animations to play slower or
* faster. Defaults to 1.
* <p>
* See TrackEntry {@link TrackEntry#getTimeScale()} for affecting a single animation. */
public float getTimeScale () {
return timeScale;
}
public void setTimeScale (float timeScale) {
this.timeScale = timeScale;
}
/** When false, only two animations can be mixed at once. Interrupting a mix by setting a new animation will discard one of the
* two old animations, keeping the one closest to being fully mixed in. Discarding an animation in this way may cause keyed
* values to jump.
* <p>
* When true, any number of animations can be mixed at once without causing keyed values to jump. Mixing is done by mixing out
* one or more old animations while mixing in the newest one. When animations key the same value, this may cause "dipping",
* where the value moves toward the setup pose as the old animations mix out, then back to the keyed value as the new animation
* mixes in.
* <p>
* Defaults to false. */
public boolean getMultipleMixing () {
return multipleMixing;
}
public void setMultipleMixing (boolean multipleMixing) {
this.multipleMixing = multipleMixing;
animationsChanged = true;
}
/** The AnimationStateData to look up mix durations. */
public AnimationStateData getData () {
return data;
}
public void setData (AnimationStateData data) {
if (data == null) throw new IllegalArgumentException("data cannot be null.");
this.data = data;
}
/** The list of tracks that currently have animations, which may contain null entries. */
public Array<TrackEntry> getTracks () {
return tracks;
}
public String toString () {
StringBuilder buffer = new StringBuilder(64);
for (int i = 0, n = tracks.size; i < n; i++) {
TrackEntry entry = tracks.get(i);
if (entry == null) continue;
if (buffer.length() > 0) buffer.append(", ");
buffer.append(entry.toString());
}
if (buffer.length() == 0) return "<none>";
return buffer.toString();
}
/** Stores settings and other state for the playback of an animation on an {@link AnimationState} track.
* <p>
* References to a track entry must not be kept after the {@link AnimationStateListener#dispose(TrackEntry)} event occurs. */
static public class TrackEntry implements Poolable {
Animation animation;
TrackEntry next, mixingFrom;
AnimationStateListener listener;
int trackIndex;
boolean loop;
float eventThreshold, attachmentThreshold, drawOrderThreshold;
float animationStart, animationEnd, animationLast, nextAnimationLast;
float delay, trackTime, trackLast, nextTrackLast, trackEnd, timeScale;
float alpha, mixTime, mixDuration, mixAlpha;
final BooleanArray timelinesFirst = new BooleanArray(), timelinesLast = new BooleanArray();
final FloatArray timelinesRotation = new FloatArray();
public void reset () {
next = null;
mixingFrom = null;
animation = null;
listener = null;
timelinesFirst.clear();
timelinesLast.clear();
timelinesRotation.clear();
}
/** The index of the track where this track entry is either current or queued.
* <p>
* See {@link AnimationState#getCurrent(int)}. */
public int getTrackIndex () {
return trackIndex;
}
/** The animation to apply for this track entry. */
public Animation getAnimation () {
return animation;
}
public void setAnimation (Animation animation) {
this.animation = animation;
}
/** If true, the animation will repeat. If false it will not, instead its last frame is applied if played beyond its
* duration. */
public boolean getLoop () {
return loop;
}
public void setLoop (boolean loop) {
this.loop = loop;
}
/** Seconds to postpone playing the animation. When a track entry is the current track entry, <code>delay</code> postpones
* incrementing the {@link #getTrackTime()}. When a track entry is queued, <code>delay</code> is the time from the start of
* the previous animation to when the track entry will become the current track entry. */
public float getDelay () {
return delay;
}
public void setDelay (float delay) {
this.delay = delay;
}
/** Current time in seconds this track entry has been the current track entry. The track time determines
* {@link #getAnimationTime()}. The track time can be set to start the animation at a time other than 0, without affecting
* looping. */
public float getTrackTime () {
return trackTime;
}
public void setTrackTime (float trackTime) {
this.trackTime = trackTime;
}
/** The track time in seconds when this animation will be removed from the track. Defaults to the highest possible float
* value, meaning the animation will be applied until a new animation is set or the track is cleared. If the track end time
* is reached, no other animations are queued for playback, and mixing from any previous animations is complete, then the
* properties keyed by the animation are set to the setup pose and the track is cleared.
* <p>
* It may be desired to use {@link AnimationState#addEmptyAnimation(int, float, float)} to mix the properties back to the
* setup pose over time, rather than have it happen instantly. */
public float getTrackEnd () {
return trackEnd;
}
public void setTrackEnd (float trackEnd) {
this.trackEnd = trackEnd;
}
/** Seconds when this animation starts, both initially and after looping. Defaults to 0.
* <p>
* When changing the <code>animationStart</code> time, it often makes sense to set {@link #getAnimationLast()} to the same
* value to prevent timeline keys before the start time from triggering. */
public float getAnimationStart () {
return animationStart;
}
public void setAnimationStart (float animationStart) {
this.animationStart = animationStart;
}
/** Seconds for the last frame of this animation. Non-looping animations won't play past this time. Looping animations will
* loop back to {@link #getAnimationStart()} at this time. Defaults to the animation {@link Animation#duration}. */
public float getAnimationEnd () {
return animationEnd;
}
public void setAnimationEnd (float animationEnd) {
this.animationEnd = animationEnd;
}
/** The time in seconds this animation was last applied. Some timelines use this for one-time triggers. Eg, when this
* animation is applied, event timelines will fire all events between the <code>animationLast</code> time (exclusive) and
* <code>animationTime</code> (inclusive). Defaults to -1 to ensure triggers on frame 0 happen the first time this animation
* is applied. */
public float getAnimationLast () {
return animationLast;
}
public void setAnimationLast (float animationLast) {
this.animationLast = animationLast;
nextAnimationLast = animationLast;
}
/** Uses {@link #getTrackTime()} to compute the <code>animationTime</code>, which is between {@link #getAnimationStart()}
* and {@link #getAnimationEnd()}. When the <code>trackTime</code> is 0, the <code>animationTime</code> is equal to the
* <code>animationStart</code> time. */
public float getAnimationTime () {
if (loop) {
float duration = animationEnd - animationStart;
if (duration == 0) return animationStart;
return (trackTime % duration) + animationStart;
}
return Math.min(trackTime + animationStart, animationEnd);
}
/** Multiplier for the delta time when the animation state is updated, causing time for this animation to pass slower or
* faster. Defaults to 1.
* <p>
* See AnimationState {@link AnimationState#getTimeScale()} for affecting all animations. */
public float getTimeScale () {
return timeScale;
}
public void setTimeScale (float timeScale) {
this.timeScale = timeScale;
}
/** The listener for events generated by this track entry, or null.
* <p>
* A track entry returned from {@link AnimationState#setAnimation(int, Animation, boolean)} is already the current animation
* for the track, so the track entry listener {@link AnimationStateListener#start(TrackEntry)} will not be called. */
public AnimationStateListener getListener () {
return listener;
}
/** @param listener May be null. */
public void setListener (AnimationStateListener listener) {
this.listener = listener;
}
/** Values < 1 mix this animation with the setup pose or the skeleton's previous pose. Defaults to 1, which overwrites the
* skeleton's previous pose with this animation.
* <p>
* Typically track 0 is used to completely pose the skeleton, then alpha can be used on higher tracks. It doesn't make sense
* to use alpha on track 0 if the skeleton pose is from the last frame render. */
public float getAlpha () {
return alpha;
}
public void setAlpha (float alpha) {
this.alpha = alpha;
}
/** When the mix percentage ({@link #getMixTime()} / {@link #getMixDuration()}) is less than the
* <code>eventThreshold</code>, event timelines for the animation being mixed out will be applied. Defaults to 0, so event
* timelines are not applied for an animation being mixed out. */
public float getEventThreshold () {
return eventThreshold;
}
public void setEventThreshold (float eventThreshold) {
this.eventThreshold = eventThreshold;
}
/** When the mix percentage ({@link #getMixTime()} / {@link #getMixDuration()}) is less than the
* <code>attachmentThreshold</code>, attachment timelines for the animation being mixed out will be applied. Defaults to 0,
* so attachment timelines are not applied for an animation being mixed out. */
public float getAttachmentThreshold () {
return attachmentThreshold;
}
public void setAttachmentThreshold (float attachmentThreshold) {
this.attachmentThreshold = attachmentThreshold;
}
/** When the mix percentage ({@link #getMixTime()} / {@link #getMixDuration()}) is less than the
* <code>drawOrderThreshold</code>, draw order timelines for the animation being mixed out will be applied. Defaults to 0,
* so draw order timelines are not applied for an animation being mixed out. */
public float getDrawOrderThreshold () {
return drawOrderThreshold;
}
public void setDrawOrderThreshold (float drawOrderThreshold) {
this.drawOrderThreshold = drawOrderThreshold;
}
/** The animation queued to start after this animation, or null. <code>next</code> makes up a linked list. */
public TrackEntry getNext () {
return next;
}
/** Returns true if at least one loop has been completed.
* <p>
* See {@link AnimationStateListener#complete(TrackEntry)}. */
public boolean isComplete () {
return trackTime >= animationEnd - animationStart;
}
/** Seconds from 0 to the {@link #getMixDuration()} when mixing from the previous animation to this animation. May be
* slightly more than <code>mixDuration</code> when the mix is complete. The mix time can be set manually rather than use
* the value from AnimationStateData {@link AnimationStateData#getMix(Animation, Animation)}. */
public float getMixTime () {
return mixTime;
}
public void setMixTime (float mixTime) {
this.mixTime = mixTime;
}
/** Seconds for mixing from the previous animation to this animation. Defaults to the value provided by AnimationStateData
* {@link AnimationStateData#getMix(Animation, Animation)} based on the animation before this animation (if any).
* <p>
* The <code>mixDuration</code> must be set for a new track entry before {@link AnimationState#update(float)} is next
* called.
* <p>
* When using {@link AnimationState#addAnimation(int, Animation, boolean, float)} with a <code>delay</code> <= 0, note the
* {@link #getDelay()} is set using the mix duration from the {@link AnimationStateData}. */
public float getMixDuration () {
return mixDuration;
}
public void setMixDuration (float mixDuration) {
this.mixDuration = mixDuration;
}
/** The track entry for the previous animation when mixing from the previous animation to this animation, or null if no
* mixing is currently occuring. If mixing from multiple animations, <code>mixingFrom</code> makes up a linked list. */
public TrackEntry getMixingFrom () {