SkeletonUtility.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. #if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
  30. #define NEW_PREFAB_SYSTEM
  31. #endif
  32. using System.Collections.Generic;
  33. using UnityEngine;
  34. namespace Spine.Unity {
  35. #if NEW_PREFAB_SYSTEM
  36. [ExecuteAlways]
  37. #else
  38. [ExecuteInEditMode]
  39. #endif
  40. [RequireComponent(typeof(ISkeletonAnimation))]
  41. [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonUtility")]
  42. public sealed class SkeletonUtility : MonoBehaviour {
  43. #region BoundingBoxAttachment
  44. public static PolygonCollider2D AddBoundingBoxGameObject (Skeleton skeleton, string skinName, string slotName, string attachmentName, Transform parent, bool isTrigger = true) {
  45. Skin skin = string.IsNullOrEmpty(skinName) ? skeleton.Data.DefaultSkin : skeleton.Data.FindSkin(skinName);
  46. if (skin == null) {
  47. Debug.LogError("Skin " + skinName + " not found!");
  48. return null;
  49. }
  50. Slot slot = skeleton.FindSlot(slotName);
  51. var attachment = slot != null ? skin.GetAttachment(slot.Data.Index, attachmentName) : null;
  52. if (attachment == null) {
  53. Debug.LogFormat("Attachment in slot '{0}' named '{1}' not found in skin '{2}'.", slotName, attachmentName, skin.Name);
  54. return null;
  55. }
  56. var box = attachment as BoundingBoxAttachment;
  57. if (box != null) {
  58. return AddBoundingBoxGameObject(box.Name, box, slot, parent, isTrigger);
  59. } else {
  60. Debug.LogFormat("Attachment '{0}' was not a Bounding Box.", attachmentName);
  61. return null;
  62. }
  63. }
  64. public static PolygonCollider2D AddBoundingBoxGameObject (string name, BoundingBoxAttachment box, Slot slot, Transform parent, bool isTrigger = true) {
  65. var go = new GameObject("[BoundingBox]" + (string.IsNullOrEmpty(name) ? box.Name : name));
  66. #if UNITY_EDITOR
  67. if (!Application.isPlaying)
  68. UnityEditor.Undo.RegisterCreatedObjectUndo(go, "Spawn BoundingBox");
  69. #endif
  70. var got = go.transform;
  71. got.parent = parent;
  72. got.localPosition = Vector3.zero;
  73. got.localRotation = Quaternion.identity;
  74. got.localScale = Vector3.one;
  75. return AddBoundingBoxAsComponent(box, slot, go, isTrigger);
  76. }
  77. public static PolygonCollider2D AddBoundingBoxAsComponent (BoundingBoxAttachment box, Slot slot, GameObject gameObject, bool isTrigger = true) {
  78. if (box == null) return null;
  79. var collider = gameObject.AddComponent<PolygonCollider2D>();
  80. collider.isTrigger = isTrigger;
  81. SetColliderPointsLocal(collider, slot, box);
  82. return collider;
  83. }
  84. public static void SetColliderPointsLocal (PolygonCollider2D collider, Slot slot, BoundingBoxAttachment box, float scale = 1.0f) {
  85. if (box == null) return;
  86. if (box.IsWeighted()) Debug.LogWarning("UnityEngine.PolygonCollider2D does not support weighted or animated points. Collider points will not be animated and may have incorrect orientation. If you want to use it as a collider, please remove weights and animations from the bounding box in Spine editor.");
  87. var verts = box.GetLocalVertices(slot, null);
  88. if (scale != 1.0f) {
  89. for (int i = 0, n = verts.Length; i < n; ++i)
  90. verts[i] *= scale;
  91. }
  92. collider.SetPath(0, verts);
  93. }
  94. public static Bounds GetBoundingBoxBounds (BoundingBoxAttachment boundingBox, float depth = 0) {
  95. float[] floats = boundingBox.Vertices;
  96. int floatCount = floats.Length;
  97. Bounds bounds = new Bounds();
  98. bounds.center = new Vector3(floats[0], floats[1], 0);
  99. for (int i = 2; i < floatCount; i += 2)
  100. bounds.Encapsulate(new Vector3(floats[i], floats[i + 1], 0));
  101. Vector3 size = bounds.size;
  102. size.z = depth;
  103. bounds.size = size;
  104. return bounds;
  105. }
  106. public static Rigidbody2D AddBoneRigidbody2D (GameObject gameObject, bool isKinematic = true, float gravityScale = 0f) {
  107. var rb = gameObject.GetComponent<Rigidbody2D>();
  108. if (rb == null) {
  109. rb = gameObject.AddComponent<Rigidbody2D>();
  110. rb.isKinematic = isKinematic;
  111. rb.gravityScale = gravityScale;
  112. }
  113. return rb;
  114. }
  115. #endregion
  116. public delegate void SkeletonUtilityDelegate ();
  117. public event SkeletonUtilityDelegate OnReset;
  118. public Transform boneRoot;
  119. /// <summary>
  120. /// If true, <see cref="Skeleton.ScaleX"/> and <see cref="Skeleton.ScaleY"/> are followed
  121. /// by 180 degree rotation. If false, negative Transform scale is used.
  122. /// Note that using negative scale is consistent with previous behaviour (hence the default),
  123. /// however causes serious problems with rigidbodies and physics. Therefore, it is recommended to
  124. /// enable this parameter where possible. When creating hinge chains for a chain of skeleton bones
  125. /// via <see cref="SkeletonUtilityBone"/>, it is mandatory to have <c>flipBy180DegreeRotation</c> enabled.
  126. /// </summary>
  127. public bool flipBy180DegreeRotation = false;
  128. void Update () {
  129. var skeleton = skeletonComponent.Skeleton;
  130. if (skeleton != null && boneRoot != null) {
  131. if (flipBy180DegreeRotation) {
  132. boneRoot.localScale = new Vector3(Mathf.Abs(skeleton.ScaleX), Mathf.Abs(skeleton.ScaleY), 1f);
  133. boneRoot.eulerAngles = new Vector3(skeleton.ScaleY > 0 ? 0 : 180,
  134. skeleton.ScaleX > 0 ? 0 : 180,
  135. 0);
  136. } else {
  137. boneRoot.localScale = new Vector3(skeleton.ScaleX, skeleton.ScaleY, 1f);
  138. }
  139. }
  140. if (canvas != null) {
  141. positionScale = canvas.referencePixelsPerUnit;
  142. }
  143. }
  144. [HideInInspector] public SkeletonRenderer skeletonRenderer;
  145. [HideInInspector] public SkeletonGraphic skeletonGraphic;
  146. private Canvas canvas;
  147. [System.NonSerialized] public ISkeletonAnimation skeletonAnimation;
  148. private ISkeletonComponent skeletonComponent;
  149. [System.NonSerialized] public List<SkeletonUtilityBone> boneComponents = new List<SkeletonUtilityBone>();
  150. [System.NonSerialized] public List<SkeletonUtilityConstraint> constraintComponents = new List<SkeletonUtilityConstraint>();
  151. public ISkeletonComponent SkeletonComponent {
  152. get {
  153. if (skeletonComponent == null) {
  154. skeletonComponent = skeletonRenderer != null ? skeletonRenderer.GetComponent<ISkeletonComponent>() :
  155. skeletonGraphic != null ? skeletonGraphic.GetComponent<ISkeletonComponent>() :
  156. GetComponent<ISkeletonComponent>();
  157. }
  158. return skeletonComponent;
  159. }
  160. }
  161. public Skeleton Skeleton {
  162. get {
  163. if (SkeletonComponent == null)
  164. return null;
  165. return skeletonComponent.Skeleton;
  166. }
  167. }
  168. public bool IsValid {
  169. get {
  170. return (skeletonRenderer != null && skeletonRenderer.valid) ||
  171. (skeletonGraphic != null && skeletonGraphic.IsValid);
  172. }
  173. }
  174. public float PositionScale { get { return positionScale; } }
  175. float positionScale = 1.0f;
  176. bool hasOverrideBones;
  177. bool hasConstraints;
  178. bool needToReprocessBones;
  179. public void ResubscribeEvents () {
  180. OnDisable();
  181. OnEnable();
  182. }
  183. void OnEnable () {
  184. if (skeletonRenderer == null) {
  185. skeletonRenderer = GetComponent<SkeletonRenderer>();
  186. }
  187. if (skeletonGraphic == null) {
  188. skeletonGraphic = GetComponent<SkeletonGraphic>();
  189. }
  190. if (skeletonAnimation == null) {
  191. skeletonAnimation = skeletonRenderer != null ? skeletonRenderer.GetComponent<ISkeletonAnimation>() :
  192. skeletonGraphic != null ? skeletonGraphic.GetComponent<ISkeletonAnimation>() :
  193. GetComponent<ISkeletonAnimation>();
  194. }
  195. if (skeletonComponent == null) {
  196. skeletonComponent = skeletonRenderer != null ? skeletonRenderer.GetComponent<ISkeletonComponent>() :
  197. skeletonGraphic != null ? skeletonGraphic.GetComponent<ISkeletonComponent>() :
  198. GetComponent<ISkeletonComponent>();
  199. }
  200. if (skeletonRenderer != null) {
  201. skeletonRenderer.OnRebuild -= HandleRendererReset;
  202. skeletonRenderer.OnRebuild += HandleRendererReset;
  203. } else if (skeletonGraphic != null) {
  204. skeletonGraphic.OnRebuild -= HandleRendererReset;
  205. skeletonGraphic.OnRebuild += HandleRendererReset;
  206. canvas = skeletonGraphic.canvas;
  207. if (canvas == null)
  208. canvas = skeletonGraphic.GetComponentInParent<Canvas>();
  209. if (canvas == null)
  210. positionScale = 100.0f;
  211. }
  212. if (skeletonAnimation != null) {
  213. skeletonAnimation.UpdateLocal -= UpdateLocal;
  214. skeletonAnimation.UpdateLocal += UpdateLocal;
  215. }
  216. CollectBones();
  217. }
  218. void Start () {
  219. //recollect because order of operations failure when switching between game mode and edit mode...
  220. CollectBones();
  221. }
  222. void OnDisable () {
  223. if (skeletonRenderer != null)
  224. skeletonRenderer.OnRebuild -= HandleRendererReset;
  225. if (skeletonGraphic != null)
  226. skeletonGraphic.OnRebuild -= HandleRendererReset;
  227. if (skeletonAnimation != null) {
  228. skeletonAnimation.UpdateLocal -= UpdateLocal;
  229. skeletonAnimation.UpdateWorld -= UpdateWorld;
  230. skeletonAnimation.UpdateComplete -= UpdateComplete;
  231. }
  232. }
  233. void HandleRendererReset (SkeletonRenderer r) {
  234. if (OnReset != null) OnReset();
  235. CollectBones();
  236. }
  237. void HandleRendererReset (SkeletonGraphic g) {
  238. if (OnReset != null) OnReset();
  239. CollectBones();
  240. }
  241. public void RegisterBone (SkeletonUtilityBone bone) {
  242. if (boneComponents.Contains(bone)) {
  243. return;
  244. } else {
  245. boneComponents.Add(bone);
  246. needToReprocessBones = true;
  247. }
  248. }
  249. public void UnregisterBone (SkeletonUtilityBone bone) {
  250. boneComponents.Remove(bone);
  251. }
  252. public void RegisterConstraint (SkeletonUtilityConstraint constraint) {
  253. if (constraintComponents.Contains(constraint))
  254. return;
  255. else {
  256. constraintComponents.Add(constraint);
  257. needToReprocessBones = true;
  258. }
  259. }
  260. public void UnregisterConstraint (SkeletonUtilityConstraint constraint) {
  261. constraintComponents.Remove(constraint);
  262. }
  263. public void CollectBones () {
  264. var skeleton = skeletonComponent.Skeleton;
  265. if (skeleton == null) return;
  266. if (boneRoot != null) {
  267. var constraintTargets = new List<System.Object>();
  268. var ikConstraints = skeleton.IkConstraints;
  269. for (int i = 0, n = ikConstraints.Count; i < n; i++)
  270. constraintTargets.Add(ikConstraints.Items[i].Target);
  271. var transformConstraints = skeleton.TransformConstraints;
  272. for (int i = 0, n = transformConstraints.Count; i < n; i++)
  273. constraintTargets.Add(transformConstraints.Items[i].Target);
  274. var boneComponents = this.boneComponents;
  275. for (int i = 0, n = boneComponents.Count; i < n; i++) {
  276. var b = boneComponents[i];
  277. if (b.bone == null) {
  278. b.DoUpdate(SkeletonUtilityBone.UpdatePhase.Local);
  279. if (b.bone == null) continue;
  280. }
  281. hasOverrideBones |= (b.mode == SkeletonUtilityBone.Mode.Override);
  282. hasConstraints |= constraintTargets.Contains(b.bone);
  283. }
  284. hasConstraints |= constraintComponents.Count > 0;
  285. if (skeletonAnimation != null) {
  286. skeletonAnimation.UpdateWorld -= UpdateWorld;
  287. skeletonAnimation.UpdateComplete -= UpdateComplete;
  288. if (hasOverrideBones || hasConstraints)
  289. skeletonAnimation.UpdateWorld += UpdateWorld;
  290. if (hasConstraints)
  291. skeletonAnimation.UpdateComplete += UpdateComplete;
  292. }
  293. needToReprocessBones = false;
  294. } else {
  295. boneComponents.Clear();
  296. constraintComponents.Clear();
  297. }
  298. }
  299. void UpdateLocal (ISkeletonAnimation anim) {
  300. if (needToReprocessBones)
  301. CollectBones();
  302. var boneComponents = this.boneComponents;
  303. if (boneComponents == null) return;
  304. for (int i = 0, n = boneComponents.Count; i < n; i++)
  305. boneComponents[i].transformLerpComplete = false;
  306. UpdateAllBones(SkeletonUtilityBone.UpdatePhase.Local);
  307. }
  308. void UpdateWorld (ISkeletonAnimation anim) {
  309. UpdateAllBones(SkeletonUtilityBone.UpdatePhase.World);
  310. for (int i = 0, n = constraintComponents.Count; i < n; i++)
  311. constraintComponents[i].DoUpdate();
  312. }
  313. void UpdateComplete (ISkeletonAnimation anim) {
  314. UpdateAllBones(SkeletonUtilityBone.UpdatePhase.Complete);
  315. }
  316. void UpdateAllBones (SkeletonUtilityBone.UpdatePhase phase) {
  317. if (boneRoot == null)
  318. CollectBones();
  319. var boneComponents = this.boneComponents;
  320. if (boneComponents == null) return;
  321. for (int i = 0, n = boneComponents.Count; i < n; i++)
  322. boneComponents[i].DoUpdate(phase);
  323. }
  324. public Transform GetBoneRoot () {
  325. if (boneRoot != null)
  326. return boneRoot;
  327. var boneRootObject = new GameObject("SkeletonUtility-SkeletonRoot");
  328. #if UNITY_EDITOR
  329. if (!Application.isPlaying)
  330. UnityEditor.Undo.RegisterCreatedObjectUndo(boneRootObject, "Spawn Bone");
  331. #endif
  332. if (skeletonGraphic != null)
  333. boneRootObject.AddComponent<RectTransform>();
  334. boneRoot = boneRootObject.transform;
  335. boneRoot.SetParent(transform);
  336. boneRoot.localPosition = Vector3.zero;
  337. boneRoot.localRotation = Quaternion.identity;
  338. boneRoot.localScale = Vector3.one;
  339. return boneRoot;
  340. }
  341. public GameObject SpawnRoot (SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) {
  342. GetBoneRoot();
  343. Skeleton skeleton = this.skeletonComponent.Skeleton;
  344. GameObject go = SpawnBone(skeleton.RootBone, boneRoot, mode, pos, rot, sca);
  345. CollectBones();
  346. return go;
  347. }
  348. public GameObject SpawnHierarchy (SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) {
  349. GetBoneRoot();
  350. Skeleton skeleton = this.skeletonComponent.Skeleton;
  351. GameObject go = SpawnBoneRecursively(skeleton.RootBone, boneRoot, mode, pos, rot, sca);
  352. CollectBones();
  353. return go;
  354. }
  355. public GameObject SpawnBoneRecursively (Bone bone, Transform parent, SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) {
  356. GameObject go = SpawnBone(bone, parent, mode, pos, rot, sca);
  357. ExposedList<Bone> childrenBones = bone.Children;
  358. for (int i = 0, n = childrenBones.Count; i < n; i++) {
  359. Bone child = childrenBones.Items[i];
  360. SpawnBoneRecursively(child, go.transform, mode, pos, rot, sca);
  361. }
  362. return go;
  363. }
  364. public GameObject SpawnBone (Bone bone, Transform parent, SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) {
  365. GameObject go = new GameObject(bone.Data.Name);
  366. #if UNITY_EDITOR
  367. if (!Application.isPlaying)
  368. UnityEditor.Undo.RegisterCreatedObjectUndo(go, "Spawn Bone");
  369. #endif
  370. if (skeletonGraphic != null)
  371. go.AddComponent<RectTransform>();
  372. var goTransform = go.transform;
  373. goTransform.SetParent(parent);
  374. SkeletonUtilityBone b = go.AddComponent<SkeletonUtilityBone>();
  375. b.hierarchy = this;
  376. b.position = pos;
  377. b.rotation = rot;
  378. b.scale = sca;
  379. b.mode = mode;
  380. b.zPosition = true;
  381. b.Reset();
  382. b.bone = bone;
  383. b.boneName = bone.Data.Name;
  384. b.valid = true;
  385. if (mode == SkeletonUtilityBone.Mode.Override) {
  386. if (rot) goTransform.localRotation = Quaternion.Euler(0, 0, b.bone.AppliedRotation);
  387. if (pos) goTransform.localPosition = new Vector3(b.bone.X * positionScale, b.bone.Y * positionScale, 0);
  388. goTransform.localScale = new Vector3(b.bone.ScaleX, b.bone.ScaleY, 0);
  389. }
  390. return go;
  391. }
  392. }
  393. }