SpineAnimationStateMixerBehaviour.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated July 28, 2023. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2023, 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 or
  13. * 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 THE
  27. * SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. #if UNITY_2019_1_OR_NEWER
  30. #define SPEED_INCLUDED_IN_CLIP_TIME
  31. #endif
  32. #if UNITY_EDITOR
  33. #define SPINE_EDITMODEPOSE
  34. #endif
  35. using System;
  36. using UnityEngine;
  37. using UnityEngine.Playables;
  38. using UnityEngine.Timeline;
  39. namespace Spine.Unity.Playables {
  40. public class SpineAnimationStateMixerBehaviour : PlayableBehaviour {
  41. float[] lastInputWeights;
  42. bool lastAnyClipPlaying = false;
  43. public int trackIndex;
  44. public bool unscaledTime;
  45. ScriptPlayable<SpineAnimationStateBehaviour>[] startingClips
  46. = new ScriptPlayable<SpineAnimationStateBehaviour>[2];
  47. IAnimationStateComponent animationStateComponent;
  48. bool pauseWithDirector = true;
  49. bool endAtClipEnd = true;
  50. float endMixOutDuration = 0.1f;
  51. bool isPaused = false;
  52. TrackEntry pausedTrackEntry;
  53. float previousTimeScale = 1;
  54. float rootPlayableSpeed = 1;
  55. TrackEntry timelineStartedTrackEntry;
  56. public override void OnBehaviourPause (Playable playable, FrameData info) {
  57. if (pauseWithDirector) {
  58. if (!isPaused)
  59. HandlePause(playable);
  60. isPaused = true;
  61. }
  62. }
  63. public override void OnGraphStop (Playable playable) {
  64. bool isStoppedNotPaused = playable.GetGraph().IsPlaying(); // end of track was reached or graph stopped.
  65. if (isStoppedNotPaused && endAtClipEnd)
  66. HandleClipEnd();
  67. }
  68. public override void OnBehaviourPlay (Playable playable, FrameData info) {
  69. if (isPaused)
  70. HandleResume(playable);
  71. isPaused = false;
  72. }
  73. protected void HandlePause (Playable playable) {
  74. if (animationStateComponent.IsNullOrDestroyed()) return;
  75. TrackEntry current = animationStateComponent.AnimationState.GetCurrent(trackIndex);
  76. if (current != null && current == timelineStartedTrackEntry) {
  77. previousTimeScale = current.TimeScale;
  78. current.TimeScale = 0;
  79. pausedTrackEntry = current;
  80. }
  81. }
  82. protected void HandleResume (Playable playable) {
  83. if (animationStateComponent.IsNullOrDestroyed()) return;
  84. TrackEntry current = animationStateComponent.AnimationState.GetCurrent(trackIndex);
  85. if (current != null && current == pausedTrackEntry) {
  86. current.TimeScale = previousTimeScale;
  87. }
  88. }
  89. protected void HandleClipEnd () {
  90. if (animationStateComponent.IsNullOrDestroyed()) return;
  91. AnimationState state = animationStateComponent.AnimationState;
  92. if (endAtClipEnd &&
  93. timelineStartedTrackEntry != null &&
  94. timelineStartedTrackEntry == state.GetCurrent(trackIndex)) {
  95. if (endMixOutDuration >= 0)
  96. state.SetEmptyAnimation(trackIndex, endMixOutDuration);
  97. else // pause if endMixOutDuration < 0
  98. timelineStartedTrackEntry.TimeScale = 0;
  99. timelineStartedTrackEntry = null;
  100. }
  101. }
  102. private void AdjustTrackEntryTimeScale (Playable playable, int input, TrackEntry currentTrackEntry) {
  103. if (currentTrackEntry == null)
  104. return;
  105. ScriptPlayable<SpineAnimationStateBehaviour> clipPlayable = (ScriptPlayable<SpineAnimationStateBehaviour>)playable.GetInput(input);
  106. float clipSpeed = (float)clipPlayable.GetSpeed();
  107. SpineAnimationStateBehaviour clipData = clipPlayable.GetBehaviour();
  108. if (clipData != null && clipData.animationReference != null
  109. && currentTrackEntry.Animation == clipData.animationReference.Animation) {
  110. currentTrackEntry.TimeScale = clipSpeed * rootPlayableSpeed;
  111. }
  112. }
  113. // NOTE: This function is called at runtime and edit time. Keep that in mind when setting the values of properties.
  114. public override void ProcessFrame (Playable playable, FrameData info, object playerData) {
  115. SkeletonAnimation skeletonAnimation = playerData as SkeletonAnimation;
  116. SkeletonGraphic skeletonGraphic = playerData as SkeletonGraphic;
  117. animationStateComponent = playerData as IAnimationStateComponent;
  118. ISkeletonComponent skeletonComponent = playerData as ISkeletonComponent;
  119. if (animationStateComponent.IsNullOrDestroyed() || skeletonComponent == null) return;
  120. Skeleton skeleton = skeletonComponent.Skeleton;
  121. AnimationState state = animationStateComponent.AnimationState;
  122. if (!Application.isPlaying) {
  123. #if SPINE_EDITMODEPOSE
  124. PreviewEditModePose(playable, skeletonComponent, animationStateComponent,
  125. skeletonAnimation, skeletonGraphic);
  126. #endif
  127. return;
  128. }
  129. int inputCount = playable.GetInputCount();
  130. float previousRootSpeed = rootPlayableSpeed;
  131. rootPlayableSpeed = GetRootPlayableSpeed(playable);
  132. bool rootSpeedChanged = previousRootSpeed != rootPlayableSpeed;
  133. // Ensure correct buffer size.
  134. if (this.lastInputWeights == null || this.lastInputWeights.Length < inputCount) {
  135. this.lastInputWeights = new float[inputCount];
  136. for (int i = 0; i < inputCount; i++)
  137. this.lastInputWeights[i] = default(float);
  138. }
  139. float[] lastInputWeights = this.lastInputWeights;
  140. int numStartingClips = 0;
  141. bool anyClipPlaying = false;
  142. // Check all clips. If a clip that was weight 0 turned into weight 1, call SetAnimation.
  143. for (int i = 0; i < inputCount; i++) {
  144. float lastInputWeight = lastInputWeights[i];
  145. float inputWeight = playable.GetInputWeight(i);
  146. bool clipStarted = (inputWeight > 0) && (lastInputWeight == 0 || info.seekOccurred || info.timeLooped);
  147. if (inputWeight > 0)
  148. anyClipPlaying = true;
  149. lastInputWeights[i] = inputWeight;
  150. if (clipStarted) {
  151. if (numStartingClips < 2) {
  152. ScriptPlayable<SpineAnimationStateBehaviour> clipPlayable = (ScriptPlayable<SpineAnimationStateBehaviour>)playable.GetInput(i);
  153. startingClips[numStartingClips++] = clipPlayable;
  154. }
  155. } else if (rootSpeedChanged) {
  156. TrackEntry currentEntry = state.GetCurrent(trackIndex);
  157. AdjustTrackEntryTimeScale(playable, i, currentEntry);
  158. }
  159. }
  160. // unfortunately order of clips can be wrong when two start at the same time, we have to sort clips
  161. if (numStartingClips == 2) {
  162. ScriptPlayable<SpineAnimationStateBehaviour> clipPlayable0 = startingClips[0];
  163. ScriptPlayable<SpineAnimationStateBehaviour> clipPlayable1 = startingClips[1];
  164. if (clipPlayable0.GetDuration() > clipPlayable1.GetDuration()) { // swap, clip 0 ends after clip 1
  165. startingClips[0] = clipPlayable1;
  166. startingClips[1] = clipPlayable0;
  167. }
  168. }
  169. for (int j = 0; j < numStartingClips; ++j) {
  170. ScriptPlayable<SpineAnimationStateBehaviour> clipPlayable = startingClips[j];
  171. SpineAnimationStateBehaviour clipData = clipPlayable.GetBehaviour();
  172. pauseWithDirector = !clipData.dontPauseWithDirector;
  173. endAtClipEnd = !clipData.dontEndWithClip;
  174. endMixOutDuration = clipData.endMixOutDuration;
  175. if (clipData.animationReference == null) {
  176. float mixDuration = clipData.customDuration ? GetCustomMixDuration(clipData) : state.Data.DefaultMix;
  177. state.SetEmptyAnimation(trackIndex, mixDuration);
  178. } else {
  179. if (clipData.animationReference.Animation != null) {
  180. animationStateComponent.UnscaledTime = this.unscaledTime;
  181. TrackEntry currentEntry = state.GetCurrent(trackIndex);
  182. Spine.TrackEntry trackEntry;
  183. float customMixDuration = clipData.customDuration ? GetCustomMixDuration(clipData) : 0.0f;
  184. if (currentEntry == null && customMixDuration > 0) {
  185. state.SetEmptyAnimation(trackIndex, 0); // ease in requires empty animation
  186. trackEntry = state.AddAnimation(trackIndex, clipData.animationReference.Animation, clipData.loop, 0);
  187. } else
  188. trackEntry = state.SetAnimation(trackIndex, clipData.animationReference.Animation, clipData.loop);
  189. float clipSpeed = (float)clipPlayable.GetSpeed();
  190. trackEntry.EventThreshold = clipData.eventThreshold;
  191. trackEntry.DrawOrderThreshold = clipData.drawOrderThreshold;
  192. #if SPEED_INCLUDED_IN_CLIP_TIME
  193. trackEntry.TrackTime = (float)clipPlayable.GetTime();
  194. #else
  195. trackEntry.TrackTime = (float)clipPlayable.GetTime() * rootPlayableSpeed * clipSpeed;
  196. #endif
  197. trackEntry.TimeScale = clipSpeed * rootPlayableSpeed;
  198. trackEntry.AttachmentThreshold = clipData.attachmentThreshold;
  199. trackEntry.HoldPrevious = clipData.holdPrevious;
  200. trackEntry.Alpha = clipData.alpha;
  201. if (clipData.customDuration)
  202. trackEntry.MixDuration = customMixDuration / rootPlayableSpeed;
  203. timelineStartedTrackEntry = trackEntry;
  204. }
  205. }
  206. }
  207. if (numStartingClips > 0) {
  208. if (skeletonAnimation) {
  209. skeletonAnimation.Update(0);
  210. skeletonAnimation.LateUpdate();
  211. } else if (skeletonGraphic) {
  212. skeletonGraphic.Update(0);
  213. skeletonGraphic.LateUpdate();
  214. }
  215. }
  216. startingClips[0] = startingClips[1] = ScriptPlayable<SpineAnimationStateBehaviour>.Null;
  217. if (lastAnyClipPlaying && !anyClipPlaying)
  218. HandleClipEnd();
  219. this.lastAnyClipPlaying = anyClipPlaying;
  220. }
  221. #if SPINE_EDITMODEPOSE
  222. /// <summary>Animation event callback for editor scripts when outside of play-mode.</summary>
  223. public static event AnimationState.TrackEntryEventDelegate EditorEvent;
  224. AnimationState dummyAnimationState;
  225. ExposedList<Spine.Event> editorAnimationEvents = new ExposedList<Event>();
  226. public void PreviewEditModePose (Playable playable,
  227. ISkeletonComponent skeletonComponent, IAnimationStateComponent animationStateComponent,
  228. SkeletonAnimation skeletonAnimation, SkeletonGraphic skeletonGraphic) {
  229. if (Application.isPlaying) return;
  230. if (animationStateComponent.IsNullOrDestroyed() || skeletonComponent == null) return;
  231. editorAnimationEvents.Clear(false);
  232. int inputCount = playable.GetInputCount();
  233. float rootSpeed = GetRootPlayableSpeed(playable);
  234. int lastNonZeroWeightTrack = -1;
  235. for (int i = 0; i < inputCount; i++) {
  236. float inputWeight = playable.GetInputWeight(i);
  237. if (inputWeight > 0) lastNonZeroWeightTrack = i;
  238. }
  239. if (lastNonZeroWeightTrack != -1) {
  240. ScriptPlayable<SpineAnimationStateBehaviour> inputPlayableClip =
  241. (ScriptPlayable<SpineAnimationStateBehaviour>)playable.GetInput(lastNonZeroWeightTrack);
  242. SpineAnimationStateBehaviour clipData = inputPlayableClip.GetBehaviour();
  243. Skeleton skeleton = skeletonComponent.Skeleton;
  244. bool skeletonDataMismatch = clipData.animationReference != null && clipData.animationReference.SkeletonDataAsset &&
  245. skeletonComponent.SkeletonDataAsset.GetSkeletonData(true) != clipData.animationReference.SkeletonDataAsset.GetSkeletonData(true);
  246. if (skeletonDataMismatch) {
  247. Debug.LogWarningFormat("SpineAnimationStateMixerBehaviour tried to apply an animation for the wrong skeleton. Expected {0}. Was {1}",
  248. skeletonComponent.SkeletonDataAsset, clipData.animationReference.SkeletonDataAsset);
  249. }
  250. // Getting the from-animation here because it's required to get the mix information from AnimationStateData.
  251. Animation fromAnimation = null;
  252. float fromClipTime = 0;
  253. bool fromClipLoop = false;
  254. if (lastNonZeroWeightTrack != 0 && inputCount > 1) {
  255. var fromClip = (ScriptPlayable<SpineAnimationStateBehaviour>)playable.GetInput(lastNonZeroWeightTrack - 1);
  256. SpineAnimationStateBehaviour fromClipData = fromClip.GetBehaviour();
  257. fromAnimation = fromClipData.animationReference != null ? fromClipData.animationReference.Animation : null;
  258. #if SPEED_INCLUDED_IN_CLIP_TIME
  259. fromClipTime = (float)fromClip.GetTime();
  260. #else
  261. fromClipTime = (float)fromClip.GetTime() * (float)fromClip.GetSpeed() * rootSpeed;
  262. #endif
  263. fromClipLoop = fromClipData.loop;
  264. }
  265. Animation toAnimation = clipData.animationReference != null ? clipData.animationReference.Animation : null;
  266. #if SPEED_INCLUDED_IN_CLIP_TIME
  267. float toClipTime = (float)inputPlayableClip.GetTime();
  268. #else
  269. float toClipTime = (float)inputPlayableClip.GetTime() * (float)inputPlayableClip.GetSpeed() * rootSpeed;
  270. #endif
  271. float mixDuration = clipData.mixDuration;
  272. if (!clipData.customDuration && fromAnimation != null && toAnimation != null) {
  273. mixDuration = animationStateComponent.AnimationState.Data.GetMix(fromAnimation, toAnimation);
  274. }
  275. if (trackIndex == 0)
  276. skeleton.SetToSetupPose();
  277. // Approximate what AnimationState might do at runtime.
  278. if (fromAnimation != null && mixDuration > 0 && toClipTime < mixDuration) {
  279. dummyAnimationState = dummyAnimationState ?? new AnimationState(skeletonComponent.SkeletonDataAsset.GetAnimationStateData());
  280. TrackEntry toEntry = dummyAnimationState.GetCurrent(0);
  281. TrackEntry fromEntry = toEntry != null ? toEntry.MixingFrom : null;
  282. bool isAnimationTransitionMatch = (toEntry != null && toEntry.Animation == toAnimation && fromEntry != null && fromEntry.Animation == fromAnimation);
  283. if (!isAnimationTransitionMatch) {
  284. dummyAnimationState.ClearTracks();
  285. fromEntry = dummyAnimationState.SetAnimation(0, fromAnimation, fromClipLoop);
  286. fromEntry.AllowImmediateQueue();
  287. if (toAnimation != null) {
  288. toEntry = dummyAnimationState.SetAnimation(0, toAnimation, clipData.loop);
  289. toEntry.HoldPrevious = clipData.holdPrevious;
  290. toEntry.Alpha = clipData.alpha;
  291. }
  292. }
  293. // Update track times.
  294. fromEntry.TrackTime = fromClipTime;
  295. if (toEntry != null) {
  296. toEntry.TrackTime = toClipTime;
  297. toEntry.MixTime = toClipTime;
  298. }
  299. // Apply Pose
  300. dummyAnimationState.Event += EditorEvent;
  301. dummyAnimationState.Update(0);
  302. dummyAnimationState.Apply(skeleton);
  303. dummyAnimationState.Event -= EditorEvent;
  304. } else {
  305. if (toAnimation != null) {
  306. toAnimation.Apply(skeleton, 0, toClipTime, clipData.loop, editorAnimationEvents, clipData.alpha, MixBlend.Setup, MixDirection.In);
  307. if (EditorEvent != null) {
  308. foreach (Spine.Event e in editorAnimationEvents) {
  309. EditorEvent(null, e);
  310. }
  311. }
  312. }
  313. }
  314. skeleton.UpdateWorldTransform(Skeleton.Physics.Update);
  315. if (skeletonAnimation) {
  316. skeletonAnimation.AfterAnimationApplied();
  317. skeletonAnimation.LateUpdate();
  318. } else if (skeletonGraphic) {
  319. skeletonGraphic.AfterAnimationApplied();
  320. skeletonGraphic.LateUpdate();
  321. }
  322. }
  323. // Do nothing outside of the first clip and the last clip.
  324. }
  325. #endif
  326. float GetRootPlayableSpeed (Playable playable) {
  327. PlayableGraph graph = playable.GetGraph();
  328. int rootPlayableCount = graph.GetRootPlayableCount();
  329. if (rootPlayableCount == 1)
  330. return (float)graph.GetRootPlayable(0).GetSpeed();
  331. else {
  332. for (int rootIndex = 0; rootIndex < rootPlayableCount; ++rootIndex) {
  333. Playable rootPlayable = graph.GetRootPlayable(rootIndex);
  334. for (int i = 0, n = rootPlayable.GetInputCount(); i < n; ++i) {
  335. Playable playableChild = rootPlayable.GetInput(i);
  336. if (playableChild.Equals(playable)) {
  337. return (float)rootPlayable.GetSpeed();
  338. }
  339. }
  340. }
  341. }
  342. return 1.0f;
  343. }
  344. float GetCustomMixDuration (SpineAnimationStateBehaviour clipData) {
  345. if (clipData.useBlendDuration) {
  346. TimelineClip clip = clipData.timelineClip;
  347. return (float)Math.Max(clip.blendInDuration, clip.easeInDuration);
  348. } else {
  349. return clipData.mixDuration;
  350. }
  351. }
  352. }
  353. }