SkeletonGhost.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. // Contributed by: Mitch Thompson
  30. using System.Collections.Generic;
  31. using UnityEngine;
  32. namespace Spine.Unity.Examples {
  33. [RequireComponent(typeof(SkeletonRenderer))]
  34. public class SkeletonGhost : MonoBehaviour {
  35. // Internal Settings
  36. const HideFlags GhostHideFlags = HideFlags.HideInHierarchy;
  37. const string GhostingShaderName = "Spine/Special/SkeletonGhost";
  38. [Header("Animation")]
  39. public bool ghostingEnabled = true;
  40. [Tooltip("The time between invididual ghost pieces being spawned.")]
  41. [UnityEngine.Serialization.FormerlySerializedAs("spawnRate")]
  42. public float spawnInterval = 1f / 30f;
  43. [Tooltip("Maximum number of ghosts that can exist at a time. If the fade speed is not fast enough, the oldest ghost will immediately disappear to enforce the maximum number.")]
  44. public int maximumGhosts = 10;
  45. public float fadeSpeed = 10;
  46. [Header("Rendering")]
  47. public Shader ghostShader;
  48. public Color32 color = new Color32(0xFF, 0xFF, 0xFF, 0x00); // default for additive.
  49. [Tooltip("Remember to set color alpha to 0 if Additive is true")]
  50. public bool additive = true;
  51. [Tooltip("0 is Color and Alpha, 1 is Alpha only.")]
  52. [Range(0, 1)]
  53. public float textureFade = 1;
  54. [Header("Sorting")]
  55. public bool sortWithDistanceOnly;
  56. public float zOffset = 0f;
  57. float nextSpawnTime;
  58. SkeletonGhostRenderer[] pool;
  59. int poolIndex = 0;
  60. SkeletonRenderer skeletonRenderer;
  61. MeshRenderer meshRenderer;
  62. MeshFilter meshFilter;
  63. readonly Dictionary<Material, Material> materialTable = new Dictionary<Material, Material>();
  64. void Start () {
  65. Initialize(false);
  66. }
  67. public void Initialize (bool overwrite) {
  68. if (pool == null || overwrite) {
  69. if (ghostShader == null)
  70. ghostShader = Shader.Find(GhostingShaderName);
  71. skeletonRenderer = GetComponent<SkeletonRenderer>();
  72. meshFilter = GetComponent<MeshFilter>();
  73. meshRenderer = GetComponent<MeshRenderer>();
  74. nextSpawnTime = Time.time + spawnInterval;
  75. pool = new SkeletonGhostRenderer[maximumGhosts];
  76. for (int i = 0; i < maximumGhosts; i++) {
  77. GameObject go = new GameObject(gameObject.name + " Ghost", typeof(SkeletonGhostRenderer));
  78. pool[i] = go.GetComponent<SkeletonGhostRenderer>();
  79. go.SetActive(false);
  80. go.hideFlags = GhostHideFlags;
  81. }
  82. var skeletonAnimation = skeletonRenderer as Spine.Unity.IAnimationStateComponent;
  83. if (skeletonAnimation != null)
  84. skeletonAnimation.AnimationState.Event += OnEvent;
  85. }
  86. }
  87. //SkeletonAnimation
  88. /*
  89. * Int Value: 0 sets ghostingEnabled to false, 1 sets ghostingEnabled to true
  90. * Float Value: Values greater than 0 set the spawnRate equal the float value
  91. * String Value: Pass RGBA hex color values in to set the color property. IE: "A0FF8BFF"
  92. */
  93. void OnEvent (Spine.TrackEntry trackEntry, Spine.Event e) {
  94. if (e.Data.Name.Equals("Ghosting", System.StringComparison.Ordinal)) {
  95. ghostingEnabled = e.Int > 0;
  96. if (e.Float > 0)
  97. spawnInterval = e.Float;
  98. if (!string.IsNullOrEmpty(e.String))
  99. this.color = HexToColor(e.String);
  100. }
  101. }
  102. //SkeletonAnimator
  103. //SkeletonAnimator or Mecanim based animations only support toggling ghostingEnabled. Be sure not to set anything other than the Int param in Spine or String will take priority.
  104. void Ghosting (float val) {
  105. ghostingEnabled = val > 0;
  106. }
  107. void Update () {
  108. if (!ghostingEnabled || poolIndex >= pool.Length)
  109. return;
  110. if (Time.time >= nextSpawnTime) {
  111. GameObject go = pool[poolIndex].gameObject;
  112. Material[] materials = meshRenderer.sharedMaterials;
  113. for (int i = 0; i < materials.Length; i++) {
  114. var originalMat = materials[i];
  115. Material ghostMat;
  116. if (!materialTable.ContainsKey(originalMat)) {
  117. ghostMat = new Material(originalMat) {
  118. shader = ghostShader,
  119. color = Color.white
  120. };
  121. if (ghostMat.HasProperty("_TextureFade"))
  122. ghostMat.SetFloat("_TextureFade", textureFade);
  123. materialTable.Add(originalMat, ghostMat);
  124. } else {
  125. ghostMat = materialTable[originalMat];
  126. }
  127. materials[i] = ghostMat;
  128. }
  129. var goTransform = go.transform;
  130. goTransform.parent = transform;
  131. pool[poolIndex].Initialize(meshFilter.sharedMesh, materials, color, additive, fadeSpeed, meshRenderer.sortingLayerID, (sortWithDistanceOnly) ? meshRenderer.sortingOrder : meshRenderer.sortingOrder - 1);
  132. goTransform.localPosition = new Vector3(0f, 0f, zOffset);
  133. goTransform.localRotation = Quaternion.identity;
  134. goTransform.localScale = Vector3.one;
  135. goTransform.parent = null;
  136. poolIndex++;
  137. if (poolIndex == pool.Length)
  138. poolIndex = 0;
  139. nextSpawnTime = Time.time + spawnInterval;
  140. }
  141. }
  142. void OnDestroy () {
  143. if (pool != null) {
  144. for (int i = 0; i < maximumGhosts; i++)
  145. if (pool[i] != null) pool[i].Cleanup();
  146. }
  147. foreach (var mat in materialTable.Values)
  148. Destroy(mat);
  149. }
  150. // based on UnifyWiki http://wiki.unity3d.com/index.php?title=HexConverter
  151. static Color32 HexToColor (string hex) {
  152. const System.Globalization.NumberStyles HexNumber = System.Globalization.NumberStyles.HexNumber;
  153. if (hex.Length < 6)
  154. return Color.magenta;
  155. hex = hex.Replace("#", "");
  156. byte r = byte.Parse(hex.Substring(0, 2), HexNumber);
  157. byte g = byte.Parse(hex.Substring(2, 2), HexNumber);
  158. byte b = byte.Parse(hex.Substring(4, 2), HexNumber);
  159. byte a = 0xFF;
  160. if (hex.Length == 8)
  161. a = byte.Parse(hex.Substring(6, 2), HexNumber);
  162. return new Color32(r, g, b, a);
  163. }
  164. }
  165. }