源战役客户端
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

331 行
14 KiB

  1. /******************************************************************************
  2. * Spine Runtimes Software License v2.5
  3. *
  4. * Copyright (c) 2013-2016, Esoteric Software
  5. * All rights reserved.
  6. *
  7. * You are granted a perpetual, non-exclusive, non-sublicensable, and
  8. * non-transferable license to use, install, execute, and perform the Spine
  9. * Runtimes software and derivative works solely for personal or internal
  10. * use. Without the written permission of Esoteric Software (see Section 2 of
  11. * the Spine Software License Agreement), you may not (a) modify, translate,
  12. * adapt, or develop new applications using the Spine Runtimes or otherwise
  13. * create derivative works or improvements of the Spine Runtimes or (b) remove,
  14. * delete, alter, or obscure any trademarks or any copyright, trademark, patent,
  15. * or other intellectual property or proprietary rights notices on or in the
  16. * Software, including any copy thereof. Redistributions in binary or source
  17. * form must include this license and terms.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
  20. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  21. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  22. * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  24. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
  25. * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  26. * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  27. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. * POSSIBILITY OF SUCH DAMAGE.
  29. *****************************************************************************/
  30. #define SPINE_OPTIONAL_RENDEROVERRIDE
  31. #define SPINE_OPTIONAL_MATERIALOVERRIDE
  32. using System.Collections.Generic;
  33. using UnityEngine;
  34. namespace Spine.Unity {
  35. /// <summary>Renders a skeleton.</summary>
  36. [ExecuteInEditMode, RequireComponent(typeof(MeshFilter), typeof(MeshRenderer)), DisallowMultipleComponent]
  37. [HelpURL("http://esotericsoftware.com/spine-unity-documentation#Rendering")]
  38. public class SkeletonRenderer : MonoBehaviour, ISkeletonComponent, IHasSkeletonDataAsset {
  39. public delegate void SkeletonRendererDelegate (SkeletonRenderer skeletonRenderer);
  40. public event SkeletonRendererDelegate OnRebuild;
  41. /// <summary> Occurs after the vertex data is populated every frame, before the vertices are pushed into the mesh.</summary>
  42. public event Spine.Unity.MeshGeneratorDelegate OnPostProcessVertices;
  43. public SkeletonDataAsset skeletonDataAsset;
  44. public SkeletonDataAsset SkeletonDataAsset { get { return skeletonDataAsset; } } // ISkeletonComponent
  45. public string initialSkinName;
  46. public bool initialFlipX, initialFlipY;
  47. #region Advanced
  48. // Submesh Separation
  49. [UnityEngine.Serialization.FormerlySerializedAs("submeshSeparators")] [SpineSlot] public string[] separatorSlotNames = new string[0];
  50. [System.NonSerialized] public readonly List<Slot> separatorSlots = new List<Slot>();
  51. [Range(-0.1f, 0f)] public float zSpacing;
  52. //public bool renderMeshes = true;
  53. public bool useClipping = true;
  54. public bool immutableTriangles = false;
  55. public bool pmaVertexColors = true;
  56. /// <summary>Clears the state when this component or its GameObject is disabled. This prevents previous state from being retained when it is enabled again. When pooling your skeleton, setting this to true can be helpful.</summary>
  57. public bool clearStateOnDisable = false;
  58. public bool tintBlack = false;
  59. public bool singleSubmesh = false;
  60. [UnityEngine.Serialization.FormerlySerializedAs("calculateNormals")]
  61. public bool addNormals = false;
  62. public bool calculateTangents = false;
  63. public bool logErrors = false;
  64. #if SPINE_OPTIONAL_RENDEROVERRIDE
  65. public bool disableRenderingOnOverride = true;
  66. public delegate void InstructionDelegate (SkeletonRendererInstruction instruction);
  67. event InstructionDelegate generateMeshOverride;
  68. public event InstructionDelegate GenerateMeshOverride {
  69. add {
  70. generateMeshOverride += value;
  71. if (disableRenderingOnOverride && generateMeshOverride != null) {
  72. Initialize(false);
  73. meshRenderer.enabled = false;
  74. }
  75. }
  76. remove {
  77. generateMeshOverride -= value;
  78. if (disableRenderingOnOverride && generateMeshOverride == null) {
  79. Initialize(false);
  80. meshRenderer.enabled = true;
  81. }
  82. }
  83. }
  84. #endif
  85. #if SPINE_OPTIONAL_MATERIALOVERRIDE
  86. [System.NonSerialized] readonly Dictionary<Material, Material> customMaterialOverride = new Dictionary<Material, Material>();
  87. public Dictionary<Material, Material> CustomMaterialOverride { get { return customMaterialOverride; } }
  88. #endif
  89. // Custom Slot Material
  90. [System.NonSerialized] readonly Dictionary<Slot, Material> customSlotMaterials = new Dictionary<Slot, Material>();
  91. public Dictionary<Slot, Material> CustomSlotMaterials { get { return customSlotMaterials; } }
  92. #endregion
  93. MeshRenderer meshRenderer;
  94. MeshFilter meshFilter;
  95. [System.NonSerialized] public bool valid;
  96. [System.NonSerialized] public Skeleton skeleton;
  97. public Skeleton Skeleton {
  98. get {
  99. Initialize(false);
  100. return skeleton;
  101. }
  102. }
  103. [System.NonSerialized] readonly SkeletonRendererInstruction currentInstructions = new SkeletonRendererInstruction();
  104. readonly MeshGenerator meshGenerator = new MeshGenerator();
  105. [System.NonSerialized] readonly MeshRendererBuffers rendererBuffers = new MeshRendererBuffers();
  106. #region Runtime Instantiation
  107. public static T NewSpineGameObject<T> (SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer {
  108. return SkeletonRenderer.AddSpineComponent<T>(new GameObject("New Spine GameObject"), skeletonDataAsset);
  109. }
  110. /// <summary>Add and prepare a Spine component that derives from SkeletonRenderer to a GameObject at runtime.</summary>
  111. /// <typeparam name="T">T should be SkeletonRenderer or any of its derived classes.</typeparam>
  112. public static T AddSpineComponent<T> (GameObject gameObject, SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer {
  113. var c = gameObject.AddComponent<T>();
  114. if (skeletonDataAsset != null) {
  115. c.skeletonDataAsset = skeletonDataAsset;
  116. c.Initialize(false);
  117. }
  118. return c;
  119. }
  120. /// <summary>Applies MeshGenerator settings to the SkeletonRenderer and its internal MeshGenerator.</summary>
  121. public void SetMeshSettings (MeshGenerator.Settings settings) {
  122. this.calculateTangents = settings.calculateTangents;
  123. this.immutableTriangles = settings.immutableTriangles;
  124. this.pmaVertexColors = settings.pmaVertexColors;
  125. this.tintBlack = settings.tintBlack;
  126. this.useClipping = settings.useClipping;
  127. this.zSpacing = settings.zSpacing;
  128. this.meshGenerator.settings = settings;
  129. }
  130. #endregion
  131. public virtual void Awake () {
  132. Initialize(false);
  133. }
  134. void OnDisable () {
  135. if (clearStateOnDisable && valid)
  136. ClearState();
  137. }
  138. void OnDestroy () {
  139. rendererBuffers.Dispose();
  140. valid = false;
  141. }
  142. /// <summary>
  143. /// Clears the previously generated mesh and resets the skeleton's pose.</summary>
  144. public virtual void ClearState () {
  145. meshFilter.sharedMesh = null;
  146. currentInstructions.Clear();
  147. if (skeleton != null) skeleton.SetToSetupPose();
  148. }
  149. public void EnsureMeshGeneratorCapacity (int minimumVertexCount) {
  150. meshGenerator.EnsureVertexCapacity(minimumVertexCount);
  151. }
  152. /// <summary>
  153. /// Initialize this component. Attempts to load the SkeletonData and creates the internal Skeleton object and buffers.</summary>
  154. /// <param name="overwrite">If set to <c>true</c>, it will overwrite internal objects if they were already generated. Otherwise, the initialized component will ignore subsequent calls to initialize.</param>
  155. public virtual void Initialize (bool overwrite) {
  156. if (valid && !overwrite)
  157. return;
  158. // Clear
  159. {
  160. if (meshFilter != null)
  161. meshFilter.sharedMesh = null;
  162. meshRenderer = GetComponent<MeshRenderer>();
  163. if (meshRenderer != null) meshRenderer.sharedMaterial = null;
  164. currentInstructions.Clear();
  165. rendererBuffers.Clear();
  166. meshGenerator.Begin();
  167. skeleton = null;
  168. valid = false;
  169. }
  170. if (!skeletonDataAsset) {
  171. if (logErrors) Debug.LogError("Missing SkeletonData asset.", this);
  172. return;
  173. }
  174. SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false);
  175. if (skeletonData == null) return;
  176. valid = true;
  177. meshFilter = GetComponent<MeshFilter>();
  178. meshRenderer = GetComponent<MeshRenderer>();
  179. rendererBuffers.Initialize();
  180. skeleton = new Skeleton(skeletonData) {
  181. flipX = initialFlipX,
  182. flipY = initialFlipY
  183. };
  184. if (!string.IsNullOrEmpty(initialSkinName) && !string.Equals(initialSkinName, "default", System.StringComparison.Ordinal))
  185. skeleton.SetSkin(initialSkinName);
  186. separatorSlots.Clear();
  187. for (int i = 0; i < separatorSlotNames.Length; i++)
  188. separatorSlots.Add(skeleton.FindSlot(separatorSlotNames[i]));
  189. LateUpdate(); // Generate mesh for the first frame it exists.
  190. if (OnRebuild != null)
  191. OnRebuild(this);
  192. }
  193. /// <summary>
  194. /// Generates a new UnityEngine.Mesh from the internal Skeleton.</summary>
  195. public virtual void LateUpdate () {
  196. if (!valid) return;
  197. #if SPINE_OPTIONAL_RENDEROVERRIDE
  198. bool doMeshOverride = generateMeshOverride != null;
  199. if ((!meshRenderer.enabled) && !doMeshOverride) return;
  200. #else
  201. const bool doMeshOverride = false;
  202. if (!meshRenderer.enabled) return;
  203. #endif
  204. var currentInstructions = this.currentInstructions;
  205. var workingSubmeshInstructions = currentInstructions.submeshInstructions;
  206. var currentSmartMesh = rendererBuffers.GetNextMesh(); // Double-buffer for performance.
  207. bool updateTriangles;
  208. if (this.singleSubmesh) {
  209. // STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. =============================================
  210. MeshGenerator.GenerateSingleSubmeshInstruction(currentInstructions, skeleton, skeletonDataAsset.atlasAssets[0].materials[0]);
  211. // STEP 1.9. Post-process workingInstructions. ==================================================================================
  212. #if SPINE_OPTIONAL_MATERIALOVERRIDE
  213. if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated
  214. MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride);
  215. #endif
  216. // STEP 2. Update vertex buffer based on verts from the attachments. ===========================================================
  217. meshGenerator.settings = new MeshGenerator.Settings {
  218. pmaVertexColors = this.pmaVertexColors,
  219. zSpacing = this.zSpacing,
  220. useClipping = this.useClipping,
  221. tintBlack = this.tintBlack,
  222. calculateTangents = this.calculateTangents,
  223. addNormals = this.addNormals
  224. };
  225. meshGenerator.Begin();
  226. updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed);
  227. if (currentInstructions.hasActiveClipping) {
  228. meshGenerator.AddSubmesh(workingSubmeshInstructions.Items[0], updateTriangles);
  229. } else {
  230. meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles);
  231. }
  232. } else {
  233. // STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. =============================================
  234. MeshGenerator.GenerateSkeletonRendererInstruction(currentInstructions, skeleton, customSlotMaterials, separatorSlots, doMeshOverride, this.immutableTriangles);
  235. // STEP 1.9. Post-process workingInstructions. ==================================================================================
  236. #if SPINE_OPTIONAL_MATERIALOVERRIDE
  237. if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated
  238. MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride);
  239. #endif
  240. #if SPINE_OPTIONAL_RENDEROVERRIDE
  241. if (doMeshOverride) {
  242. this.generateMeshOverride(currentInstructions);
  243. if (disableRenderingOnOverride) return;
  244. }
  245. #endif
  246. updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed);
  247. // STEP 2. Update vertex buffer based on verts from the attachments. ===========================================================
  248. meshGenerator.settings = new MeshGenerator.Settings {
  249. pmaVertexColors = this.pmaVertexColors,
  250. zSpacing = this.zSpacing,
  251. useClipping = this.useClipping,
  252. tintBlack = this.tintBlack,
  253. calculateTangents = this.calculateTangents,
  254. addNormals = this.addNormals
  255. };
  256. meshGenerator.Begin();
  257. if (currentInstructions.hasActiveClipping)
  258. meshGenerator.BuildMesh(currentInstructions, updateTriangles);
  259. else
  260. meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles);
  261. }
  262. if (OnPostProcessVertices != null) OnPostProcessVertices.Invoke(this.meshGenerator.Buffers);
  263. // STEP 3. Move the mesh data into a UnityEngine.Mesh ===========================================================================
  264. var currentMesh = currentSmartMesh.mesh;
  265. meshGenerator.FillVertexData(currentMesh);
  266. rendererBuffers.UpdateSharedMaterials(workingSubmeshInstructions);
  267. if (updateTriangles) { // Check if the triangles should also be updated.
  268. meshGenerator.FillTriangles(currentMesh);
  269. meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray();
  270. } else if (rendererBuffers.MaterialsChangedInLastUpdate()) {
  271. meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray();
  272. }
  273. meshGenerator.FillLateVertexData(currentMesh);
  274. // STEP 4. The UnityEngine.Mesh is ready. Set it as the MeshFilter's mesh. Store the instructions used for that mesh. ===========
  275. meshFilter.sharedMesh = currentMesh;
  276. currentSmartMesh.instructionUsed.Set(currentInstructions);
  277. }
  278. }
  279. }