ball 项目提交
This commit is contained in:
@@ -0,0 +1,808 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated January 1, 2020. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2020, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software
|
||||
* or otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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
|
||||
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
#if UNITY_2019_3_OR_NEWER
|
||||
#define CONFIGURABLE_ENTER_PLAY_MODE
|
||||
#endif
|
||||
|
||||
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
using System;
|
||||
|
||||
|
||||
namespace Spine.Unity.AttachmentTools {
|
||||
|
||||
public static class AtlasUtilities {
|
||||
internal const TextureFormat SpineTextureFormat = TextureFormat.RGBA32;
|
||||
internal const float DefaultMipmapBias = -0.5f;
|
||||
internal const bool UseMipMaps = false;
|
||||
internal const float DefaultScale = 0.01f;
|
||||
|
||||
const int NonrenderingRegion = -1;
|
||||
|
||||
#if CONFIGURABLE_ENTER_PLAY_MODE
|
||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
|
||||
static void Init () {
|
||||
// handle disabled domain reload
|
||||
AtlasUtilities.ClearCache();
|
||||
}
|
||||
#endif
|
||||
|
||||
public static AtlasRegion ToAtlasRegion (this Texture2D t, Material materialPropertySource, float scale = DefaultScale) {
|
||||
return t.ToAtlasRegion(materialPropertySource.shader, scale, materialPropertySource);
|
||||
}
|
||||
|
||||
public static AtlasRegion ToAtlasRegion (this Texture2D t, Shader shader, float scale = DefaultScale, Material materialPropertySource = null) {
|
||||
var material = new Material(shader);
|
||||
if (materialPropertySource != null) {
|
||||
material.CopyPropertiesFromMaterial(materialPropertySource);
|
||||
material.shaderKeywords = materialPropertySource.shaderKeywords;
|
||||
}
|
||||
|
||||
material.mainTexture = t;
|
||||
var page = material.ToSpineAtlasPage();
|
||||
|
||||
float width = t.width;
|
||||
float height = t.height;
|
||||
|
||||
var region = new AtlasRegion();
|
||||
region.name = t.name;
|
||||
region.index = -1;
|
||||
region.rotate = false;
|
||||
|
||||
// World space units
|
||||
Vector2 boundsMin = Vector2.zero, boundsMax = new Vector2(width, height) * scale;
|
||||
|
||||
// Texture space/pixel units
|
||||
region.width = (int)width;
|
||||
region.originalWidth = (int)width;
|
||||
region.height = (int)height;
|
||||
region.originalHeight = (int)height;
|
||||
region.offsetX = width * (0.5f - InverseLerp(boundsMin.x, boundsMax.x, 0));
|
||||
region.offsetY = height * (0.5f - InverseLerp(boundsMin.y, boundsMax.y, 0));
|
||||
|
||||
// Use the full area of the texture.
|
||||
region.u = 0;
|
||||
region.v = 1;
|
||||
region.u2 = 1;
|
||||
region.v2 = 0;
|
||||
region.x = 0;
|
||||
region.y = 0;
|
||||
|
||||
region.page = page;
|
||||
|
||||
return region;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary>
|
||||
public static AtlasRegion ToAtlasRegionPMAClone (this Texture2D t, Material materialPropertySource, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) {
|
||||
return t.ToAtlasRegionPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary>
|
||||
public static AtlasRegion ToAtlasRegionPMAClone (this Texture2D t, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null) {
|
||||
var material = new Material(shader);
|
||||
if (materialPropertySource != null) {
|
||||
material.CopyPropertiesFromMaterial(materialPropertySource);
|
||||
material.shaderKeywords = materialPropertySource.shaderKeywords;
|
||||
}
|
||||
var newTexture = t.GetClone(textureFormat, mipmaps, applyPMA : true);
|
||||
|
||||
newTexture.name = t.name + "-pma-";
|
||||
material.name = t.name + shader.name;
|
||||
|
||||
material.mainTexture = newTexture;
|
||||
var page = material.ToSpineAtlasPage();
|
||||
|
||||
var region = newTexture.ToAtlasRegion(shader);
|
||||
region.page = page;
|
||||
|
||||
return region;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new Spine.AtlasPage from a UnityEngine.Material. If the material has a preassigned texture, the page width and height will be set.</summary>
|
||||
public static AtlasPage ToSpineAtlasPage (this Material m) {
|
||||
var newPage = new AtlasPage {
|
||||
rendererObject = m,
|
||||
name = m.name
|
||||
};
|
||||
|
||||
var t = m.mainTexture;
|
||||
if (t != null) {
|
||||
newPage.width = t.width;
|
||||
newPage.height = t.height;
|
||||
}
|
||||
|
||||
return newPage;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Spine.AtlasRegion from a UnityEngine.Sprite.</summary>
|
||||
public static AtlasRegion ToAtlasRegion (this Sprite s, AtlasPage page) {
|
||||
if (page == null) throw new System.ArgumentNullException("page", "page cannot be null. AtlasPage determines which texture region belongs and how it should be rendered. You can use material.ToSpineAtlasPage() to get a shareable AtlasPage from a Material, or use the sprite.ToAtlasRegion(material) overload.");
|
||||
var region = s.ToAtlasRegion();
|
||||
region.page = page;
|
||||
return region;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Spine.AtlasRegion from a UnityEngine.Sprite. This creates a new AtlasPage object for every AtlasRegion you create. You can centralize Material control by creating a shared atlas page using Material.ToSpineAtlasPage and using the sprite.ToAtlasRegion(AtlasPage) overload.</summary>
|
||||
public static AtlasRegion ToAtlasRegion (this Sprite s, Material material) {
|
||||
var region = s.ToAtlasRegion();
|
||||
region.page = material.ToSpineAtlasPage();
|
||||
return region;
|
||||
}
|
||||
|
||||
public static AtlasRegion ToAtlasRegionPMAClone (this Sprite s, Material materialPropertySource, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) {
|
||||
return s.ToAtlasRegionPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary>
|
||||
public static AtlasRegion ToAtlasRegionPMAClone (this Sprite s, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null) {
|
||||
var material = new Material(shader);
|
||||
if (materialPropertySource != null) {
|
||||
material.CopyPropertiesFromMaterial(materialPropertySource);
|
||||
material.shaderKeywords = materialPropertySource.shaderKeywords;
|
||||
}
|
||||
|
||||
var tex = s.ToTexture(textureFormat, mipmaps, applyPMA : true);
|
||||
tex.name = s.name + "-pma-";
|
||||
material.name = tex.name + shader.name;
|
||||
|
||||
material.mainTexture = tex;
|
||||
var page = material.ToSpineAtlasPage();
|
||||
|
||||
var region = s.ToAtlasRegion(true);
|
||||
region.page = page;
|
||||
|
||||
return region;
|
||||
}
|
||||
|
||||
internal static AtlasRegion ToAtlasRegion (this Sprite s, bool isolatedTexture = false) {
|
||||
var region = new AtlasRegion();
|
||||
region.name = s.name;
|
||||
region.index = -1;
|
||||
region.rotate = s.packed && s.packingRotation != SpritePackingRotation.None;
|
||||
|
||||
// World space units
|
||||
Bounds bounds = s.bounds;
|
||||
Vector2 boundsMin = bounds.min, boundsMax = bounds.max;
|
||||
|
||||
// Texture space/pixel units
|
||||
Rect spineRect = s.rect.SpineUnityFlipRect(s.texture.height);
|
||||
region.width = (int)spineRect.width;
|
||||
region.originalWidth = (int)spineRect.width;
|
||||
region.height = (int)spineRect.height;
|
||||
region.originalHeight = (int)spineRect.height;
|
||||
region.offsetX = spineRect.width * (0.5f - InverseLerp(boundsMin.x, boundsMax.x, 0));
|
||||
region.offsetY = spineRect.height * (0.5f - InverseLerp(boundsMin.y, boundsMax.y, 0));
|
||||
|
||||
if (isolatedTexture) {
|
||||
region.u = 0;
|
||||
region.v = 1;
|
||||
region.u2 = 1;
|
||||
region.v2 = 0;
|
||||
region.x = 0;
|
||||
region.y = 0;
|
||||
} else {
|
||||
Texture2D tex = s.texture;
|
||||
Rect uvRect = TextureRectToUVRect(s.textureRect, tex.width, tex.height);
|
||||
region.u = uvRect.xMin;
|
||||
region.v = uvRect.yMax;
|
||||
region.u2 = uvRect.xMax;
|
||||
region.v2 = uvRect.yMin;
|
||||
region.x = (int)spineRect.x;
|
||||
region.y = (int)spineRect.y;
|
||||
}
|
||||
|
||||
return region;
|
||||
}
|
||||
|
||||
#region Runtime Repacking
|
||||
static readonly Dictionary<AtlasRegion, int> existingRegions = new Dictionary<AtlasRegion, int>();
|
||||
static readonly List<int> regionIndices = new List<int>();
|
||||
static readonly List<Texture2D> texturesToPack = new List<Texture2D>();
|
||||
static readonly List<AtlasRegion> originalRegions = new List<AtlasRegion>();
|
||||
static readonly List<AtlasRegion> repackedRegions = new List<AtlasRegion>();
|
||||
static readonly List<Attachment> repackedAttachments = new List<Attachment>();
|
||||
static List<Texture2D>[] texturesToPackAtParam = new List<Texture2D>[1];
|
||||
|
||||
/// <summary>
|
||||
/// Fills the outputAttachments list with new attachment objects based on the attachments in sourceAttachments,
|
||||
/// but mapped to a new single texture using the same material.</summary>
|
||||
/// <remarks>Returned <c>Material</c> and <c>Texture</c> behave like <c>new Texture2D()</c>, thus you need to call <c>Destroy()</c>
|
||||
/// to free resources.
|
||||
/// This method caches necessary Texture copies for later re-use, which might steadily increase the texture memory
|
||||
/// footprint when used excessively. Set <paramref name="clearCache"/> to <c>true</c>
|
||||
/// or call <see cref="AtlasUtilities.ClearCache()"/> to clear this texture cache.
|
||||
/// You may want to call <c>Resources.UnloadUnusedAssets()</c> after that.
|
||||
/// </remarks>
|
||||
/// <param name="sourceAttachments">The list of attachments to be repacked.</param>
|
||||
/// <param name = "outputAttachments">The List(Attachment) to populate with the newly created Attachment objects.</param>
|
||||
/// <param name="materialPropertySource">May be null. If no Material property source is provided, no special </param>
|
||||
/// <param name="clearCache">When set to <c>true</c>, <see cref="AtlasUtilities.ClearCache()"/> is called after
|
||||
/// repacking to clear the texture cache. See remarks for additional info.</param>
|
||||
public static void GetRepackedAttachments (List<Attachment> sourceAttachments, List<Attachment> outputAttachments, Material materialPropertySource, out Material outputMaterial, out Texture2D outputTexture, int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, string newAssetName = "Repacked Attachments", bool clearCache = false, bool useOriginalNonrenderables = true) {
|
||||
if (sourceAttachments == null) throw new System.ArgumentNullException("sourceAttachments");
|
||||
if (outputAttachments == null) throw new System.ArgumentNullException("outputAttachments");
|
||||
|
||||
// Use shared lists to detect and use shared regions.
|
||||
existingRegions.Clear();
|
||||
regionIndices.Clear();
|
||||
texturesToPack.Clear();
|
||||
originalRegions.Clear();
|
||||
|
||||
outputAttachments.Clear();
|
||||
outputAttachments.AddRange(sourceAttachments);
|
||||
|
||||
int newRegionIndex = 0;
|
||||
for (int i = 0, n = sourceAttachments.Count; i < n; i++) {
|
||||
var originalAttachment = sourceAttachments[i];
|
||||
|
||||
if (IsRenderable(originalAttachment)) {
|
||||
var newAttachment = originalAttachment.GetCopy(true);
|
||||
var region = newAttachment.GetRegion();
|
||||
int existingIndex;
|
||||
if (existingRegions.TryGetValue(region, out existingIndex)) {
|
||||
regionIndices.Add(existingIndex); // Store the region index for the eventual new attachment.
|
||||
} else {
|
||||
originalRegions.Add(region);
|
||||
texturesToPack.Add(region.ToTexture(textureFormat, mipmaps)); // Add the texture to the PackTextures argument
|
||||
existingRegions.Add(region, newRegionIndex); // Add the region to the dictionary of known regions
|
||||
regionIndices.Add(newRegionIndex); // Store the region index for the eventual new attachment.
|
||||
newRegionIndex++;
|
||||
}
|
||||
|
||||
outputAttachments[i] = newAttachment;
|
||||
} else {
|
||||
outputAttachments[i] = useOriginalNonrenderables ? originalAttachment : originalAttachment.GetCopy(true);
|
||||
regionIndices.Add(NonrenderingRegion); // Output attachments pairs with regionIndexes list 1:1. Pad with a sentinel if the attachment doesn't have a region.
|
||||
}
|
||||
}
|
||||
|
||||
// Fill a new texture with the collected attachment textures.
|
||||
var newTexture = new Texture2D(maxAtlasSize, maxAtlasSize, textureFormat, mipmaps);
|
||||
newTexture.mipMapBias = AtlasUtilities.DefaultMipmapBias;
|
||||
newTexture.name = newAssetName;
|
||||
// Copy settings
|
||||
if (texturesToPack.Count > 0) {
|
||||
var sourceTexture = texturesToPack[0];
|
||||
newTexture.CopyTextureAttributesFrom(sourceTexture);
|
||||
}
|
||||
var rects = newTexture.PackTextures(texturesToPack.ToArray(), padding, maxAtlasSize);
|
||||
|
||||
// Rehydrate the repacked textures as a Material, Spine atlas and Spine.AtlasAttachments
|
||||
Shader shader = materialPropertySource == null ? Shader.Find("Spine/Skeleton") : materialPropertySource.shader;
|
||||
var newMaterial = new Material(shader);
|
||||
if (materialPropertySource != null) {
|
||||
newMaterial.CopyPropertiesFromMaterial(materialPropertySource);
|
||||
newMaterial.shaderKeywords = materialPropertySource.shaderKeywords;
|
||||
}
|
||||
|
||||
newMaterial.name = newAssetName;
|
||||
newMaterial.mainTexture = newTexture;
|
||||
var page = newMaterial.ToSpineAtlasPage();
|
||||
page.name = newAssetName;
|
||||
|
||||
repackedRegions.Clear();
|
||||
for (int i = 0, n = originalRegions.Count; i < n; i++) {
|
||||
var oldRegion = originalRegions[i];
|
||||
var newRegion = UVRectToAtlasRegion(rects[i], oldRegion, page);
|
||||
repackedRegions.Add(newRegion);
|
||||
}
|
||||
|
||||
// Map the cloned attachments to the repacked atlas.
|
||||
for (int i = 0, n = outputAttachments.Count; i < n; i++) {
|
||||
var a = outputAttachments[i];
|
||||
if (IsRenderable(a))
|
||||
a.SetRegion(repackedRegions[regionIndices[i]]);
|
||||
}
|
||||
|
||||
// Clean up.
|
||||
if (clearCache)
|
||||
AtlasUtilities.ClearCache();
|
||||
|
||||
outputTexture = newTexture;
|
||||
outputMaterial = newMaterial;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates and populates a duplicate skin with cloned attachments that are backed by a new packed texture atlas
|
||||
/// comprised of all the regions from the original skin.</summary>
|
||||
/// <remarks>GetRepackedSkin is an expensive operation, preferably call it at level load time.
|
||||
/// No Spine.Atlas object is created so there is no way to find AtlasRegions except through the Attachments using them.
|
||||
/// Returned <c>Material</c> and <c>Texture</c> behave like <c>new Texture2D()</c>, thus you need to call <c>Destroy()</c>
|
||||
/// to free resources.
|
||||
/// This method caches necessary Texture copies for later re-use, which might steadily increase the texture memory
|
||||
/// footprint when used excessively. Set <paramref name="clearCache"/> to <c>true</c>
|
||||
/// or call <see cref="AtlasUtilities.ClearCache()"/> to clear this texture cache.
|
||||
/// You may want to call <c>Resources.UnloadUnusedAssets()</c> after that.
|
||||
/// </remarks>
|
||||
/// <param name="clearCache">When set to <c>true</c>, <see cref="AtlasUtilities.ClearCache()"/> is called after
|
||||
/// repacking to clear the texture cache. See remarks for additional info.</param>
|
||||
/// <param name="additionalTexturePropertyIDsToCopy">Optional additional textures (such as normal maps) to copy while repacking.
|
||||
/// To copy e.g. the main texture and normal maps, pass 'new int[] { Shader.PropertyToID("_BumpMap") }' at this parameter.</param>
|
||||
/// <param name="additionalOutputTextures">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
|
||||
/// this array will be filled with the resulting repacked texture for every property,
|
||||
/// just as the main repacked texture is assigned to <c>outputTexture</c>.</param>
|
||||
/// <param name="additionalTextureFormats">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
|
||||
/// this array will be used as <c>TextureFormat</c> at the Texture at the respective property.
|
||||
/// When <c>additionalTextureFormats</c> is <c>null</c> or when its array size is smaller,
|
||||
/// <c>textureFormat</c> is used where there exists no corresponding array item.</param>
|
||||
/// <param name="additionalTextureIsLinear">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
|
||||
/// this array will be used to determine whether <c>linear</c> or <c>sRGB</c> color space is used at the
|
||||
/// Texture at the respective property. When <c>additionalTextureIsLinear</c> is <c>null</c>, <c>linear</c> color space
|
||||
/// is assumed at every additional Texture element.
|
||||
/// When e.g. packing the main texture and normal maps, pass 'new bool[] { true }' at this parameter, because normal maps use
|
||||
/// linear color space.</param>
|
||||
public static Skin GetRepackedSkin (this Skin o, string newName, Material materialPropertySource, out Material outputMaterial, out Texture2D outputTexture,
|
||||
int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps,
|
||||
bool useOriginalNonrenderables = true, bool clearCache = false,
|
||||
int[] additionalTexturePropertyIDsToCopy = null, Texture2D[] additionalOutputTextures = null,
|
||||
TextureFormat[] additionalTextureFormats = null, bool[] additionalTextureIsLinear = null) {
|
||||
|
||||
return GetRepackedSkin(o, newName, materialPropertySource.shader, out outputMaterial, out outputTexture,
|
||||
maxAtlasSize, padding, textureFormat, mipmaps, materialPropertySource,
|
||||
clearCache, useOriginalNonrenderables, additionalTexturePropertyIDsToCopy, additionalOutputTextures,
|
||||
additionalTextureFormats, additionalTextureIsLinear);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates and populates a duplicate skin with cloned attachments that are backed by a new packed texture atlas
|
||||
/// comprised of all the regions from the original skin.</summary>
|
||||
/// See documentation of <see cref="GetRepackedSkin"/> for details.
|
||||
public static Skin GetRepackedSkin (this Skin o, string newName, Shader shader, out Material outputMaterial, out Texture2D outputTexture,
|
||||
int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps,
|
||||
Material materialPropertySource = null, bool clearCache = false, bool useOriginalNonrenderables = true,
|
||||
int[] additionalTexturePropertyIDsToCopy = null, Texture2D[] additionalOutputTextures = null,
|
||||
TextureFormat[] additionalTextureFormats = null, bool[] additionalTextureIsLinear = null) {
|
||||
|
||||
outputTexture = null;
|
||||
if (additionalTexturePropertyIDsToCopy != null && additionalTextureIsLinear == null) {
|
||||
additionalTextureIsLinear = new bool[additionalTexturePropertyIDsToCopy.Length];
|
||||
for (int i = 0; i < additionalTextureIsLinear.Length; ++i) {
|
||||
additionalTextureIsLinear[i] = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (o == null) throw new System.NullReferenceException("Skin was null");
|
||||
var skinAttachments = o.Attachments;
|
||||
var newSkin = new Skin(newName);
|
||||
|
||||
newSkin.bones.AddRange(o.bones);
|
||||
newSkin.constraints.AddRange(o.constraints);
|
||||
|
||||
// Use these to detect and use shared regions.
|
||||
existingRegions.Clear();
|
||||
regionIndices.Clear();
|
||||
|
||||
// Collect all textures from the attachments of the original skin.
|
||||
repackedAttachments.Clear();
|
||||
int numTextureParamsToRepack = 1 + (additionalTexturePropertyIDsToCopy == null ? 0 : additionalTexturePropertyIDsToCopy.Length);
|
||||
additionalOutputTextures = (additionalTexturePropertyIDsToCopy == null ? null : new Texture2D[additionalTexturePropertyIDsToCopy.Length]);
|
||||
if (texturesToPackAtParam.Length < numTextureParamsToRepack)
|
||||
Array.Resize(ref texturesToPackAtParam, numTextureParamsToRepack);
|
||||
for (int i = 0; i < numTextureParamsToRepack; ++i) {
|
||||
if (texturesToPackAtParam[i] != null)
|
||||
texturesToPackAtParam[i].Clear();
|
||||
else
|
||||
texturesToPackAtParam[i] = new List<Texture2D>();
|
||||
}
|
||||
originalRegions.Clear();
|
||||
int newRegionIndex = 0;
|
||||
|
||||
foreach (var skinEntry in skinAttachments) {
|
||||
var originalKey = skinEntry.Key;
|
||||
var originalAttachment = skinEntry.Value;
|
||||
|
||||
Attachment newAttachment;
|
||||
if (IsRenderable(originalAttachment)) {
|
||||
newAttachment = originalAttachment.GetCopy(true);
|
||||
var region = newAttachment.GetRegion();
|
||||
int existingIndex;
|
||||
if (existingRegions.TryGetValue(region, out existingIndex)) {
|
||||
regionIndices.Add(existingIndex); // Store the region index for the eventual new attachment.
|
||||
} else {
|
||||
originalRegions.Add(region);
|
||||
for (int i = 0; i < numTextureParamsToRepack; ++i) {
|
||||
Texture2D regionTexture = (i == 0 ?
|
||||
region.ToTexture(textureFormat, mipmaps) :
|
||||
region.ToTexture((additionalTextureFormats != null && i - 1 < additionalTextureFormats.Length) ?
|
||||
additionalTextureFormats[i - 1] : textureFormat,
|
||||
mipmaps, additionalTexturePropertyIDsToCopy[i - 1], additionalTextureIsLinear[i - 1]));
|
||||
texturesToPackAtParam[i].Add(regionTexture); // Add the texture to the PackTextures argument
|
||||
}
|
||||
existingRegions.Add(region, newRegionIndex); // Add the region to the dictionary of known regions
|
||||
regionIndices.Add(newRegionIndex); // Store the region index for the eventual new attachment.
|
||||
newRegionIndex++;
|
||||
}
|
||||
|
||||
repackedAttachments.Add(newAttachment);
|
||||
newSkin.SetAttachment(originalKey.SlotIndex, originalKey.Name, newAttachment);
|
||||
} else {
|
||||
newSkin.SetAttachment(originalKey.SlotIndex, originalKey.Name, useOriginalNonrenderables ? originalAttachment : originalAttachment.GetCopy(true));
|
||||
}
|
||||
}
|
||||
|
||||
// Rehydrate the repacked textures as a Material, Spine atlas and Spine.AtlasAttachments
|
||||
var newMaterial = new Material(shader);
|
||||
if (materialPropertySource != null) {
|
||||
newMaterial.CopyPropertiesFromMaterial(materialPropertySource);
|
||||
newMaterial.shaderKeywords = materialPropertySource.shaderKeywords;
|
||||
}
|
||||
newMaterial.name = newName;
|
||||
|
||||
Rect[] rects = null;
|
||||
for (int i = 0; i < numTextureParamsToRepack; ++i) {
|
||||
// Fill a new texture with the collected attachment textures.
|
||||
var newTexture = new Texture2D(maxAtlasSize, maxAtlasSize,
|
||||
(i > 0 && additionalTextureFormats != null && i - 1 < additionalTextureFormats.Length) ?
|
||||
additionalTextureFormats[i - 1] : textureFormat,
|
||||
mipmaps,
|
||||
(i > 0) ? additionalTextureIsLinear[i - 1] : false);
|
||||
newTexture.mipMapBias = AtlasUtilities.DefaultMipmapBias;
|
||||
var texturesToPack = texturesToPackAtParam[i];
|
||||
if (texturesToPack.Count > 0) {
|
||||
var sourceTexture = texturesToPack[0];
|
||||
newTexture.CopyTextureAttributesFrom(sourceTexture);
|
||||
}
|
||||
newTexture.name = newName;
|
||||
var rectsForTexParam = newTexture.PackTextures(texturesToPack.ToArray(), padding, maxAtlasSize);
|
||||
if (i == 0) {
|
||||
rects = rectsForTexParam;
|
||||
newMaterial.mainTexture = newTexture;
|
||||
outputTexture = newTexture;
|
||||
}
|
||||
else {
|
||||
newMaterial.SetTexture(additionalTexturePropertyIDsToCopy[i - 1], newTexture);
|
||||
additionalOutputTextures[i - 1] = newTexture;
|
||||
}
|
||||
}
|
||||
|
||||
var page = newMaterial.ToSpineAtlasPage();
|
||||
page.name = newName;
|
||||
|
||||
repackedRegions.Clear();
|
||||
for (int i = 0, n = originalRegions.Count; i < n; i++) {
|
||||
var oldRegion = originalRegions[i];
|
||||
var newRegion = UVRectToAtlasRegion(rects[i], oldRegion, page);
|
||||
repackedRegions.Add(newRegion);
|
||||
}
|
||||
|
||||
// Map the cloned attachments to the repacked atlas.
|
||||
for (int i = 0, n = repackedAttachments.Count; i < n; i++) {
|
||||
var a = repackedAttachments[i];
|
||||
if (IsRenderable(a))
|
||||
a.SetRegion(repackedRegions[regionIndices[i]]);
|
||||
}
|
||||
|
||||
// Clean up.
|
||||
if (clearCache)
|
||||
AtlasUtilities.ClearCache();
|
||||
|
||||
outputMaterial = newMaterial;
|
||||
return newSkin;
|
||||
}
|
||||
|
||||
public static Sprite ToSprite (this AtlasRegion ar, float pixelsPerUnit = 100) {
|
||||
return Sprite.Create(ar.GetMainTexture(), ar.GetUnityRect(), new Vector2(0.5f, 0.5f), pixelsPerUnit);
|
||||
}
|
||||
|
||||
struct IntAndAtlasRegionKey {
|
||||
int i;
|
||||
AtlasRegion region;
|
||||
|
||||
public IntAndAtlasRegionKey(int i, AtlasRegion region) {
|
||||
this.i = i;
|
||||
this.region = region;
|
||||
}
|
||||
|
||||
public override int GetHashCode () {
|
||||
return i.GetHashCode() * 23 ^ region.GetHashCode();
|
||||
}
|
||||
}
|
||||
static Dictionary<IntAndAtlasRegionKey, Texture2D> CachedRegionTextures = new Dictionary<IntAndAtlasRegionKey, Texture2D>();
|
||||
static List<Texture2D> CachedRegionTexturesList = new List<Texture2D>();
|
||||
|
||||
/// <summary>
|
||||
/// Frees up textures cached by repacking and remapping operations.
|
||||
///
|
||||
/// Calling <see cref="AttachmentCloneExtensions.GetRemappedClone"/> with parameter <c>premultiplyAlpha=true</c>,
|
||||
/// <see cref="GetRepackedAttachments"/> or <see cref="GetRepackedSkin"/> will cache textures for later re-use,
|
||||
/// which might steadily increase the texture memory footprint when used excessively.
|
||||
/// You can clear this Texture cache by calling <see cref="AtlasUtilities.ClearCache()"/>.
|
||||
/// You may also want to call <c>Resources.UnloadUnusedAssets()</c> after that. Be aware that while this cleanup
|
||||
/// frees up memory, it is also a costly operation and will likely cause a spike in the framerate.
|
||||
/// Thus it is recommended to perform costly repacking and cleanup operations after e.g. a character customization
|
||||
/// screen has been exited, and if required additionally after a certain number of <c>GetRemappedClone()</c> calls.
|
||||
/// </summary>
|
||||
public static void ClearCache () {
|
||||
foreach (var t in CachedRegionTexturesList) {
|
||||
UnityEngine.Object.Destroy(t);
|
||||
}
|
||||
CachedRegionTextures.Clear();
|
||||
CachedRegionTexturesList.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Creates a new Texture2D object based on an AtlasRegion.
|
||||
/// If applyImmediately is true, Texture2D.Apply is called immediately after the Texture2D is filled with data.</summary>
|
||||
public static Texture2D ToTexture (this AtlasRegion ar, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps,
|
||||
int texturePropertyId = 0, bool linear = false, bool applyPMA = false) {
|
||||
|
||||
Texture2D output;
|
||||
|
||||
IntAndAtlasRegionKey cacheKey = new IntAndAtlasRegionKey(texturePropertyId, ar);
|
||||
CachedRegionTextures.TryGetValue(cacheKey, out output);
|
||||
if (output == null) {
|
||||
Texture2D sourceTexture = texturePropertyId == 0 ? ar.GetMainTexture() : ar.GetTexture(texturePropertyId);
|
||||
Rect r = ar.GetUnityRect();
|
||||
// Compensate any image resizing due to Texture 'Max Size' import settings.
|
||||
// sourceTexture.width returns the resized image dimensions, at least in newer Unity versions.
|
||||
if (sourceTexture.width < ar.page.width) {
|
||||
float scaleX = (float)(sourceTexture.width) / (float)(ar.page.width);
|
||||
float scaleY = (float)(sourceTexture.height) / (float)(ar.page.height);
|
||||
var scale = new Vector2(scaleX, scaleY);
|
||||
r = new Rect(Vector2.Scale(r.position, scale), Vector2.Scale(r.size, scale));
|
||||
}
|
||||
|
||||
int width = (int)r.width;
|
||||
int height = (int)r.height;
|
||||
output = new Texture2D(width, height, textureFormat, mipmaps, linear) { name = ar.name };
|
||||
output.CopyTextureAttributesFrom(sourceTexture);
|
||||
if (applyPMA)
|
||||
AtlasUtilities.CopyTextureApplyPMA(sourceTexture, r, output);
|
||||
else
|
||||
AtlasUtilities.CopyTexture(sourceTexture, r, output);
|
||||
CachedRegionTextures.Add(cacheKey, output);
|
||||
CachedRegionTexturesList.Add(output);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
static Texture2D ToTexture (this Sprite s, TextureFormat textureFormat = SpineTextureFormat,
|
||||
bool mipmaps = UseMipMaps, bool linear = false, bool applyPMA = false) {
|
||||
|
||||
var spriteTexture = s.texture;
|
||||
Rect r;
|
||||
if (!s.packed || s.packingMode == SpritePackingMode.Rectangle) {
|
||||
r = s.textureRect;
|
||||
}
|
||||
else {
|
||||
r = new Rect();
|
||||
r.xMin = Math.Min(s.uv[0].x, s.uv[1].x) * spriteTexture.width;
|
||||
r.xMax = Math.Max(s.uv[0].x, s.uv[1].x) * spriteTexture.width;
|
||||
r.yMin = Math.Min(s.uv[0].y, s.uv[2].y) * spriteTexture.height;
|
||||
r.yMax = Math.Max(s.uv[0].y, s.uv[2].y) * spriteTexture.height;
|
||||
#if UNITY_EDITOR
|
||||
if (s.uv.Length > 4) {
|
||||
Debug.LogError("When using a tightly packed SpriteAtlas with Spine, you may only access Sprites that are packed as 'FullRect' from it! " +
|
||||
"You can either disable 'Tight Packing' at the whole SpriteAtlas, or change the single Sprite's TextureImporter Setting 'MeshType' to 'Full Rect'." +
|
||||
"Sprite Asset: " + s.name, s);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
var newTexture = new Texture2D((int)r.width, (int)r.height, textureFormat, mipmaps, linear);
|
||||
newTexture.CopyTextureAttributesFrom(spriteTexture);
|
||||
if (applyPMA)
|
||||
AtlasUtilities.CopyTextureApplyPMA(spriteTexture, r, newTexture);
|
||||
else
|
||||
AtlasUtilities.CopyTexture(spriteTexture, r, newTexture);
|
||||
return newTexture;
|
||||
}
|
||||
|
||||
static Texture2D GetClone (this Texture2D t, TextureFormat textureFormat = SpineTextureFormat,
|
||||
bool mipmaps = UseMipMaps, bool linear = false, bool applyPMA = false) {
|
||||
|
||||
var newTexture = new Texture2D((int)t.width, (int)t.height, textureFormat, mipmaps, linear);
|
||||
newTexture.CopyTextureAttributesFrom(t);
|
||||
if (applyPMA)
|
||||
AtlasUtilities.CopyTextureApplyPMA(t, new Rect(0, 0, t.width, t.height), newTexture);
|
||||
else
|
||||
AtlasUtilities.CopyTexture(t, new Rect(0, 0, t.width, t.height), newTexture);
|
||||
return newTexture;
|
||||
}
|
||||
|
||||
static void CopyTexture (Texture2D source, Rect sourceRect, Texture2D destination) {
|
||||
if (SystemInfo.copyTextureSupport == UnityEngine.Rendering.CopyTextureSupport.None) {
|
||||
// GetPixels fallback for old devices.
|
||||
Color[] pixelBuffer = source.GetPixels((int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height);
|
||||
destination.SetPixels(pixelBuffer);
|
||||
destination.Apply();
|
||||
} else {
|
||||
Graphics.CopyTexture(source, 0, 0, (int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height, destination, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
static void CopyTextureApplyPMA (Texture2D source, Rect sourceRect, Texture2D destination) {
|
||||
Color[] pixelBuffer = source.GetPixels((int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height);
|
||||
for (int i = 0, n = pixelBuffer.Length; i < n; i++) {
|
||||
Color p = pixelBuffer[i];
|
||||
float a = p.a;
|
||||
p.r = p.r * a;
|
||||
p.g = p.g * a;
|
||||
p.b = p.b * a;
|
||||
pixelBuffer[i] = p;
|
||||
}
|
||||
destination.SetPixels(pixelBuffer);
|
||||
destination.Apply();
|
||||
}
|
||||
|
||||
static bool IsRenderable (Attachment a) {
|
||||
return a is IHasRendererObject;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get a rect with flipped Y so that a Spine atlas rect gets converted to a Unity Sprite rect and vice versa.</summary>
|
||||
static Rect SpineUnityFlipRect (this Rect rect, int textureHeight) {
|
||||
rect.y = textureHeight - rect.y - rect.height;
|
||||
return rect;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Rect of an AtlasRegion according to Unity texture coordinates (x-right, y-up).
|
||||
/// This overload relies on region.page.height being correctly set.</summary>
|
||||
static Rect GetUnityRect (this AtlasRegion region) {
|
||||
return region.GetSpineAtlasRect().SpineUnityFlipRect(region.page.height);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Rect of an AtlasRegion according to Unity texture coordinates (x-right, y-up).</summary>
|
||||
static Rect GetUnityRect (this AtlasRegion region, int textureHeight) {
|
||||
return region.GetSpineAtlasRect().SpineUnityFlipRect(textureHeight);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a Rect of the AtlasRegion according to Spine texture coordinates. (x-right, y-down)</summary>
|
||||
static Rect GetSpineAtlasRect (this AtlasRegion region, bool includeRotate = true) {
|
||||
if (includeRotate && (region.degrees == 90 || region.degrees == 270))
|
||||
return new Rect(region.x, region.y, region.height, region.width);
|
||||
else
|
||||
return new Rect(region.x, region.y, region.width, region.height);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Denormalize a uvRect into a texture-space Rect.</summary>
|
||||
static Rect UVRectToTextureRect (Rect uvRect, int texWidth, int texHeight) {
|
||||
uvRect.x *= texWidth;
|
||||
uvRect.width *= texWidth;
|
||||
uvRect.y *= texHeight;
|
||||
uvRect.height *= texHeight;
|
||||
return uvRect;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalize a texture Rect into UV coordinates.</summary>
|
||||
static Rect TextureRectToUVRect (Rect textureRect, int texWidth, int texHeight) {
|
||||
textureRect.x = Mathf.InverseLerp(0, texWidth, textureRect.x);
|
||||
textureRect.y = Mathf.InverseLerp(0, texHeight, textureRect.y);
|
||||
textureRect.width = Mathf.InverseLerp(0, texWidth, textureRect.width);
|
||||
textureRect.height = Mathf.InverseLerp(0, texHeight, textureRect.height);
|
||||
return textureRect;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new Spine AtlasRegion according to a Unity UV Rect (x-right, y-up, uv-normalized).</summary>
|
||||
static AtlasRegion UVRectToAtlasRegion (Rect uvRect, AtlasRegion referenceRegion, AtlasPage page) {
|
||||
var tr = UVRectToTextureRect(uvRect, page.width, page.height);
|
||||
var rr = tr.SpineUnityFlipRect(page.height);
|
||||
|
||||
int x = (int)rr.x, y = (int)rr.y;
|
||||
int w, h;
|
||||
if (referenceRegion.degrees == 90 || referenceRegion.degrees == 270) {
|
||||
w = (int)rr.height;
|
||||
h = (int)rr.width;
|
||||
} else {
|
||||
w = (int)rr.width;
|
||||
h = (int)rr.height;
|
||||
}
|
||||
|
||||
int originalW = Mathf.RoundToInt((float)w * ((float)referenceRegion.originalWidth / (float)referenceRegion.width));
|
||||
int originalH = Mathf.RoundToInt((float)h * ((float)referenceRegion.originalHeight / (float)referenceRegion.height));
|
||||
int offsetX = Mathf.RoundToInt((float)referenceRegion.offsetX * ((float)w / (float)referenceRegion.width));
|
||||
int offsetY = Mathf.RoundToInt((float)referenceRegion.offsetY * ((float)h / (float)referenceRegion.height));
|
||||
|
||||
if (referenceRegion.degrees == 270) {
|
||||
w = (int)rr.width;
|
||||
h = (int)rr.height;
|
||||
}
|
||||
|
||||
float u = uvRect.xMin;
|
||||
float u2 = uvRect.xMax;
|
||||
float v = uvRect.yMax;
|
||||
float v2 = uvRect.yMin;
|
||||
|
||||
return new AtlasRegion {
|
||||
page = page,
|
||||
name = referenceRegion.name,
|
||||
|
||||
u = u,
|
||||
u2 = u2,
|
||||
v = v,
|
||||
v2 = v2,
|
||||
|
||||
index = -1,
|
||||
|
||||
width = w,
|
||||
originalWidth = originalW,
|
||||
height = h,
|
||||
originalHeight = originalH,
|
||||
offsetX = offsetX,
|
||||
offsetY = offsetY,
|
||||
x = x,
|
||||
y = y,
|
||||
|
||||
rotate = referenceRegion.rotate,
|
||||
degrees = referenceRegion.degrees
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convenience method for getting the main texture of the material of the page of the region.</summary>
|
||||
static Texture2D GetMainTexture (this AtlasRegion region) {
|
||||
var material = (region.page.rendererObject as Material);
|
||||
return material.mainTexture as Texture2D;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convenience method for getting any texture of the material of the page of the region by texture property name.</summary>
|
||||
static Texture2D GetTexture (this AtlasRegion region, string texturePropertyName) {
|
||||
var material = (region.page.rendererObject as Material);
|
||||
return material.GetTexture(texturePropertyName) as Texture2D;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convenience method for getting any texture of the material of the page of the region by texture property id.</summary>
|
||||
static Texture2D GetTexture (this AtlasRegion region, int texturePropertyId) {
|
||||
var material = (region.page.rendererObject as Material);
|
||||
return material.GetTexture(texturePropertyId) as Texture2D;
|
||||
}
|
||||
|
||||
static void CopyTextureAttributesFrom(this Texture2D destination, Texture2D source) {
|
||||
destination.filterMode = source.filterMode;
|
||||
destination.anisoLevel = source.anisoLevel;
|
||||
#if UNITY_EDITOR
|
||||
destination.alphaIsTransparency = source.alphaIsTransparency;
|
||||
#endif
|
||||
destination.wrapModeU = source.wrapModeU;
|
||||
destination.wrapModeV = source.wrapModeV;
|
||||
destination.wrapModeW = source.wrapModeW;
|
||||
}
|
||||
#endregion
|
||||
|
||||
static float InverseLerp (float a, float b, float value) {
|
||||
return (value - a) / (b - a);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 25ceef568a3dad448bf8a14fcc326964
|
||||
timeCreated: 1563321428
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,147 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated January 1, 2020. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2020, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software
|
||||
* or otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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
|
||||
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections;
|
||||
|
||||
namespace Spine.Unity.AttachmentTools {
|
||||
|
||||
public static class AttachmentCloneExtensions {
|
||||
/// <summary>
|
||||
/// Clones the attachment.</summary>
|
||||
public static Attachment GetCopy (this Attachment o, bool cloneMeshesAsLinked) {
|
||||
var meshAttachment = o as MeshAttachment;
|
||||
if (meshAttachment != null && cloneMeshesAsLinked)
|
||||
return meshAttachment.NewLinkedMesh();
|
||||
return o.Copy();
|
||||
}
|
||||
|
||||
#region Runtime Linked MeshAttachments
|
||||
/// <summary>
|
||||
/// Returns a new linked mesh linked to this MeshAttachment. It will be mapped to the AtlasRegion provided.</summary>
|
||||
public static MeshAttachment GetLinkedMesh (this MeshAttachment o, string newLinkedMeshName, AtlasRegion region) {
|
||||
if (region == null) throw new System.ArgumentNullException("region");
|
||||
MeshAttachment mesh = o.NewLinkedMesh();
|
||||
mesh.SetRegion(region, false);
|
||||
return mesh;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a new linked mesh linked to this MeshAttachment. It will be mapped to an AtlasRegion generated from a Sprite. The AtlasRegion will be mapped to a new Material based on the shader.
|
||||
/// For better caching and batching, use GetLinkedMesh(string, AtlasRegion, bool)</summary>
|
||||
public static MeshAttachment GetLinkedMesh (this MeshAttachment o, Sprite sprite, Shader shader, Material materialPropertySource = null) {
|
||||
var m = new Material(shader);
|
||||
if (materialPropertySource != null) {
|
||||
m.CopyPropertiesFromMaterial(materialPropertySource);
|
||||
m.shaderKeywords = materialPropertySource.shaderKeywords;
|
||||
}
|
||||
return o.GetLinkedMesh(sprite.name, sprite.ToAtlasRegion());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a new linked mesh linked to this MeshAttachment. It will be mapped to an AtlasRegion generated from a Sprite. The AtlasRegion will be mapped to a new Material based on the shader.
|
||||
/// For better caching and batching, use GetLinkedMesh(string, AtlasRegion, bool)</summary>
|
||||
public static MeshAttachment GetLinkedMesh (this MeshAttachment o, Sprite sprite, Material materialPropertySource) {
|
||||
return o.GetLinkedMesh(sprite, materialPropertySource.shader, materialPropertySource);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region RemappedClone Convenience Methods
|
||||
/// <summary>
|
||||
/// Gets a clone of the attachment remapped with a sprite image.</summary>
|
||||
/// <returns>The remapped clone.</returns>
|
||||
/// <param name="o">The original attachment.</param>
|
||||
/// <param name="sprite">The sprite whose texture to use.</param>
|
||||
/// <param name="sourceMaterial">The source material used to copy the shader and material properties from.</param>
|
||||
/// <param name="premultiplyAlpha">If <c>true</c>, a premultiply alpha clone of the original texture will be created.
|
||||
/// See remarks below for additional info.</param>
|
||||
/// <param name="cloneMeshAsLinked">If <c>true</c> MeshAttachments will be cloned as linked meshes and will inherit animation from the original attachment.</param>
|
||||
/// <param name="useOriginalRegionSize">If <c>true</c> the size of the original attachment will be followed, instead of using the Sprite size.</param>
|
||||
/// <param name="pivotShiftsMeshUVCoords">If <c>true</c> and the original Attachment is a MeshAttachment, then
|
||||
/// a non-central sprite pivot will shift uv coords in the opposite direction. Vertices will not be offset in
|
||||
/// any case when the original Attachment is a MeshAttachment.</param>
|
||||
/// <param name="useOriginalRegionScale">If <c>true</c> and the original Attachment is a RegionAttachment, then
|
||||
/// the original region's scale value is used instead of the Sprite's pixels per unit property. Since uniform scale is used,
|
||||
/// x scale of the original attachment (width scale) is used, scale in y direction (height scale) is ignored.</param>
|
||||
/// <remarks>When parameter <c>premultiplyAlpha</c> is set to <c>true</c>, a premultiply alpha clone of the
|
||||
/// original texture will be created. Additionally, this PMA Texture clone is cached for later re-use,
|
||||
/// which might steadily increase the Texture memory footprint when used excessively.
|
||||
/// See <see cref="AtlasUtilities.ClearCache()"/> on how to clear these cached textures.</remarks>
|
||||
public static Attachment GetRemappedClone (this Attachment o, Sprite sprite, Material sourceMaterial,
|
||||
bool premultiplyAlpha = true, bool cloneMeshAsLinked = true, bool useOriginalRegionSize = false,
|
||||
bool pivotShiftsMeshUVCoords = true, bool useOriginalRegionScale = false) {
|
||||
var atlasRegion = premultiplyAlpha ? sprite.ToAtlasRegionPMAClone(sourceMaterial) : sprite.ToAtlasRegion(new Material(sourceMaterial) { mainTexture = sprite.texture } );
|
||||
if (!pivotShiftsMeshUVCoords && o is MeshAttachment) {
|
||||
// prevent non-central sprite pivot setting offsetX/Y and shifting uv coords out of mesh bounds
|
||||
atlasRegion.offsetX = 0;
|
||||
atlasRegion.offsetY = 0;
|
||||
}
|
||||
float scale = 1f / sprite.pixelsPerUnit;
|
||||
if (useOriginalRegionScale) {
|
||||
var regionAttachment = o as RegionAttachment;
|
||||
if (regionAttachment != null)
|
||||
scale = regionAttachment.width / regionAttachment.regionOriginalWidth;
|
||||
}
|
||||
return o.GetRemappedClone(atlasRegion, cloneMeshAsLinked, useOriginalRegionSize, scale);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a clone of the attachment remapped with an atlasRegion image.</summary>
|
||||
/// <returns>The remapped clone.</returns>
|
||||
/// <param name="o">The original attachment.</param>
|
||||
/// <param name="atlasRegion">Atlas region.</param>
|
||||
/// <param name="cloneMeshAsLinked">If <c>true</c> MeshAttachments will be cloned as linked meshes and will inherit animation from the original attachment.</param>
|
||||
/// <param name="useOriginalRegionSize">If <c>true</c> the size of the original attachment will be followed, instead of using the Sprite size.</param>
|
||||
/// <param name="scale">Unity units per pixel scale used to scale the atlas region size when not using the original region size.</param>
|
||||
public static Attachment GetRemappedClone (this Attachment o, AtlasRegion atlasRegion, bool cloneMeshAsLinked = true, bool useOriginalRegionSize = false, float scale = 0.01f) {
|
||||
var regionAttachment = o as RegionAttachment;
|
||||
if (regionAttachment != null) {
|
||||
RegionAttachment newAttachment = (RegionAttachment)regionAttachment.Copy();
|
||||
newAttachment.SetRegion(atlasRegion, false);
|
||||
if (!useOriginalRegionSize) {
|
||||
newAttachment.width = atlasRegion.width * scale;
|
||||
newAttachment.height = atlasRegion.height * scale;
|
||||
}
|
||||
newAttachment.UpdateOffset();
|
||||
return newAttachment;
|
||||
} else {
|
||||
var meshAttachment = o as MeshAttachment;
|
||||
if (meshAttachment != null) {
|
||||
MeshAttachment newAttachment = cloneMeshAsLinked ? meshAttachment.NewLinkedMesh() : (MeshAttachment)meshAttachment.Copy();
|
||||
newAttachment.SetRegion(atlasRegion);
|
||||
return newAttachment;
|
||||
}
|
||||
}
|
||||
|
||||
return o.GetCopy(true); // Non-renderable Attachments will return as normal cloned attachments.
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3431ed563b2c62f4c8c974a99365ba52
|
||||
timeCreated: 1563321428
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated January 1, 2020. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2020, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software
|
||||
* or otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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
|
||||
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections;
|
||||
|
||||
namespace Spine.Unity.AttachmentTools {
|
||||
public static class AttachmentRegionExtensions {
|
||||
#region GetRegion
|
||||
/// <summary>
|
||||
/// Tries to get the region (image) of a renderable attachment. If the attachment is not renderable, it returns null.</summary>
|
||||
public static AtlasRegion GetRegion (this Attachment attachment) {
|
||||
var renderableAttachment = attachment as IHasRendererObject;
|
||||
if (renderableAttachment != null)
|
||||
return renderableAttachment.RendererObject as AtlasRegion;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Gets the region (image) of a RegionAttachment</summary>
|
||||
public static AtlasRegion GetRegion (this RegionAttachment regionAttachment) {
|
||||
return regionAttachment.RendererObject as AtlasRegion;
|
||||
}
|
||||
|
||||
/// <summary>Gets the region (image) of a MeshAttachment</summary>
|
||||
public static AtlasRegion GetRegion (this MeshAttachment meshAttachment) {
|
||||
return meshAttachment.RendererObject as AtlasRegion;
|
||||
}
|
||||
#endregion
|
||||
#region SetRegion
|
||||
/// <summary>
|
||||
/// Tries to set the region (image) of a renderable attachment. If the attachment is not renderable, nothing is applied.</summary>
|
||||
public static void SetRegion (this Attachment attachment, AtlasRegion region, bool updateOffset = true) {
|
||||
var regionAttachment = attachment as RegionAttachment;
|
||||
if (regionAttachment != null)
|
||||
regionAttachment.SetRegion(region, updateOffset);
|
||||
|
||||
var meshAttachment = attachment as MeshAttachment;
|
||||
if (meshAttachment != null)
|
||||
meshAttachment.SetRegion(region, updateOffset);
|
||||
}
|
||||
|
||||
/// <summary>Sets the region (image) of a RegionAttachment</summary>
|
||||
public static void SetRegion (this RegionAttachment attachment, AtlasRegion region, bool updateOffset = true) {
|
||||
if (region == null) throw new System.ArgumentNullException("region");
|
||||
|
||||
// (AtlasAttachmentLoader.cs)
|
||||
attachment.RendererObject = region;
|
||||
attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.rotate);
|
||||
attachment.regionOffsetX = region.offsetX;
|
||||
attachment.regionOffsetY = region.offsetY;
|
||||
attachment.regionWidth = region.width;
|
||||
attachment.regionHeight = region.height;
|
||||
attachment.regionOriginalWidth = region.originalWidth;
|
||||
attachment.regionOriginalHeight = region.originalHeight;
|
||||
|
||||
if (updateOffset) attachment.UpdateOffset();
|
||||
}
|
||||
|
||||
/// <summary>Sets the region (image) of a MeshAttachment</summary>
|
||||
public static void SetRegion (this MeshAttachment attachment, AtlasRegion region, bool updateUVs = true) {
|
||||
if (region == null) throw new System.ArgumentNullException("region");
|
||||
|
||||
// (AtlasAttachmentLoader.cs)
|
||||
attachment.RendererObject = region;
|
||||
attachment.RegionU = region.u;
|
||||
attachment.RegionV = region.v;
|
||||
attachment.RegionU2 = region.u2;
|
||||
attachment.RegionV2 = region.v2;
|
||||
attachment.RegionRotate = region.rotate;
|
||||
attachment.RegionDegrees = region.degrees;
|
||||
attachment.regionOffsetX = region.offsetX;
|
||||
attachment.regionOffsetY = region.offsetY;
|
||||
attachment.regionWidth = region.width;
|
||||
attachment.regionHeight = region.height;
|
||||
attachment.regionOriginalWidth = region.originalWidth;
|
||||
attachment.regionOriginalHeight = region.originalHeight;
|
||||
|
||||
if (updateUVs) attachment.UpdateUVs();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Runtime RegionAttachments
|
||||
/// <summary>
|
||||
/// Creates a RegionAttachment based on a sprite. This method creates a real, usable AtlasRegion. That AtlasRegion uses a new AtlasPage with the Material provided./// </summary>
|
||||
public static RegionAttachment ToRegionAttachment (this Sprite sprite, Material material, float rotation = 0f) {
|
||||
return sprite.ToRegionAttachment(material.ToSpineAtlasPage(), rotation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a RegionAttachment based on a sprite. This method creates a real, usable AtlasRegion. That AtlasRegion uses the AtlasPage provided./// </summary>
|
||||
public static RegionAttachment ToRegionAttachment (this Sprite sprite, AtlasPage page, float rotation = 0f) {
|
||||
if (sprite == null) throw new System.ArgumentNullException("sprite");
|
||||
if (page == null) throw new System.ArgumentNullException("page");
|
||||
var region = sprite.ToAtlasRegion(page);
|
||||
var unitsPerPixel = 1f / sprite.pixelsPerUnit;
|
||||
return region.ToRegionAttachment(sprite.name, unitsPerPixel, rotation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate texture of the Sprite's texture data.
|
||||
/// Returns a RegionAttachment that uses it. Use this if you plan to use a premultiply alpha shader such as "Spine/Skeleton".</summary>
|
||||
/// <remarks>The duplicate texture is cached for later re-use. See documentation of
|
||||
/// <see cref="AttachmentCloneExtensions.GetRemappedClone"/> for additional details.</remarks>
|
||||
public static RegionAttachment ToRegionAttachmentPMAClone (this Sprite sprite, Shader shader, TextureFormat textureFormat = AtlasUtilities.SpineTextureFormat, bool mipmaps = AtlasUtilities.UseMipMaps, Material materialPropertySource = null, float rotation = 0f) {
|
||||
if (sprite == null) throw new System.ArgumentNullException("sprite");
|
||||
if (shader == null) throw new System.ArgumentNullException("shader");
|
||||
var region = sprite.ToAtlasRegionPMAClone(shader, textureFormat, mipmaps, materialPropertySource);
|
||||
var unitsPerPixel = 1f / sprite.pixelsPerUnit;
|
||||
return region.ToRegionAttachment(sprite.name, unitsPerPixel, rotation);
|
||||
}
|
||||
|
||||
public static RegionAttachment ToRegionAttachmentPMAClone (this Sprite sprite, Material materialPropertySource, TextureFormat textureFormat = AtlasUtilities.SpineTextureFormat, bool mipmaps = AtlasUtilities.UseMipMaps, float rotation = 0f) {
|
||||
return sprite.ToRegionAttachmentPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource, rotation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new RegionAttachment from a given AtlasRegion.</summary>
|
||||
public static RegionAttachment ToRegionAttachment (this AtlasRegion region, string attachmentName, float scale = 0.01f, float rotation = 0f) {
|
||||
if (string.IsNullOrEmpty(attachmentName)) throw new System.ArgumentException("attachmentName can't be null or empty.", "attachmentName");
|
||||
if (region == null) throw new System.ArgumentNullException("region");
|
||||
|
||||
// (AtlasAttachmentLoader.cs)
|
||||
var attachment = new RegionAttachment(attachmentName);
|
||||
|
||||
attachment.RendererObject = region;
|
||||
attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.rotate);
|
||||
attachment.regionOffsetX = region.offsetX;
|
||||
attachment.regionOffsetY = region.offsetY;
|
||||
attachment.regionWidth = region.width;
|
||||
attachment.regionHeight = region.height;
|
||||
attachment.regionOriginalWidth = region.originalWidth;
|
||||
attachment.regionOriginalHeight = region.originalHeight;
|
||||
|
||||
attachment.Path = region.name;
|
||||
attachment.scaleX = 1;
|
||||
attachment.scaleY = 1;
|
||||
attachment.rotation = rotation;
|
||||
|
||||
attachment.r = 1;
|
||||
attachment.g = 1;
|
||||
attachment.b = 1;
|
||||
attachment.a = 1;
|
||||
|
||||
// pass OriginalWidth and OriginalHeight because UpdateOffset uses it in its calculation.
|
||||
attachment.width = attachment.regionOriginalWidth * scale;
|
||||
attachment.height = attachment.regionOriginalHeight * scale;
|
||||
|
||||
attachment.SetColor(Color.white);
|
||||
attachment.UpdateOffset();
|
||||
return attachment;
|
||||
}
|
||||
|
||||
/// <summary> Sets the scale. Call regionAttachment.UpdateOffset to apply the change.</summary>
|
||||
public static void SetScale (this RegionAttachment regionAttachment, Vector2 scale) {
|
||||
regionAttachment.scaleX = scale.x;
|
||||
regionAttachment.scaleY = scale.y;
|
||||
}
|
||||
|
||||
/// <summary> Sets the scale. Call regionAttachment.UpdateOffset to apply the change.</summary>
|
||||
public static void SetScale (this RegionAttachment regionAttachment, float x, float y) {
|
||||
regionAttachment.scaleX = x;
|
||||
regionAttachment.scaleY = y;
|
||||
}
|
||||
|
||||
/// <summary> Sets the position offset. Call regionAttachment.UpdateOffset to apply the change.</summary>
|
||||
public static void SetPositionOffset (this RegionAttachment regionAttachment, Vector2 offset) {
|
||||
regionAttachment.x = offset.x;
|
||||
regionAttachment.y = offset.y;
|
||||
}
|
||||
|
||||
/// <summary> Sets the position offset. Call regionAttachment.UpdateOffset to apply the change.</summary>
|
||||
public static void SetPositionOffset (this RegionAttachment regionAttachment, float x, float y) {
|
||||
regionAttachment.x = x;
|
||||
regionAttachment.y = y;
|
||||
}
|
||||
|
||||
/// <summary> Sets the rotation. Call regionAttachment.UpdateOffset to apply the change.</summary>
|
||||
public static void SetRotation (this RegionAttachment regionAttachment, float rotation) {
|
||||
regionAttachment.rotation = rotation;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7e7eac783deea004e9bc403eca68a7dc
|
||||
timeCreated: 1563321428
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,324 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated January 1, 2020. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2020, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software
|
||||
* or otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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
|
||||
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
|
||||
namespace Spine.Unity {
|
||||
/// <summary>Utility class providing methods to check material settings for incorrect combinations.</summary>
|
||||
public class MaterialChecks {
|
||||
|
||||
static readonly int STRAIGHT_ALPHA_PARAM_ID = Shader.PropertyToID("_StraightAlphaInput");
|
||||
static readonly string ALPHAPREMULTIPLY_ON_KEYWORD = "_ALPHAPREMULTIPLY_ON";
|
||||
static readonly string STRAIGHT_ALPHA_KEYWORD = "_STRAIGHT_ALPHA_INPUT";
|
||||
static readonly string[] FIXED_NORMALS_KEYWORDS = {
|
||||
"_FIXED_NORMALS_VIEWSPACE",
|
||||
"_FIXED_NORMALS_VIEWSPACE_BACKFACE",
|
||||
"_FIXED_NORMALS_MODELSPACE",
|
||||
"_FIXED_NORMALS_MODELSPACE_BACKFACE",
|
||||
"_FIXED_NORMALS_WORLDSPACE"
|
||||
};
|
||||
static readonly string NORMALMAP_KEYWORD = "_NORMALMAP";
|
||||
static readonly string CANVAS_GROUP_COMPATIBLE_KEYWORD = "_CANVAS_GROUP_COMPATIBLE";
|
||||
|
||||
public static readonly string kPMANotSupportedLinearMessage =
|
||||
"\nWarning: Premultiply-alpha atlas textures not supported in Linear color space!\n\nPlease\n"
|
||||
+ "a) re-export atlas as straight alpha texture with 'premultiply alpha' unchecked\n"
|
||||
+ " (if you have already done this, please set the 'Straight Alpha Texture' Material parameter to 'true') or\n"
|
||||
+ "b) switch to Gamma color space via\nProject Settings - Player - Other Settings - Color Space.\n";
|
||||
public static readonly string kZSpacingRequiredMessage =
|
||||
"\nWarning: Z Spacing required on selected shader! Otherwise you will receive incorrect results.\n\nPlease\n"
|
||||
+ "1) make sure at least minimal 'Z Spacing' is set at the SkeletonRenderer/SkeletonAnimation component under 'Advanced' and\n"
|
||||
+ "2) ensure that the skeleton has overlapping parts on different Z depth. You can adjust this in Spine via draw order.\n";
|
||||
public static readonly string kZSpacingRecommendedMessage =
|
||||
"\nWarning: Z Spacing recommended on selected shader configuration!\n\nPlease\n"
|
||||
+ "1) make sure at least minimal 'Z Spacing' is set at the SkeletonRenderer/SkeletonAnimation component under 'Advanced' and\n"
|
||||
+ "2) ensure that the skeleton has overlapping parts on different Z depth. You can adjust this in Spine via draw order.\n";
|
||||
public static readonly string kAddNormalsMessage =
|
||||
"\nWarning: 'Add Normals' required when not using 'Fixed Normals'!\n\nPlease\n"
|
||||
+ "a) enable 'Add Normals' at the SkeletonRenderer/SkeletonAnimation component under 'Advanced' or\n"
|
||||
+ "b) enable 'Fixed Normals' at the Material.\n";
|
||||
public static readonly string kSolveTangentsMessage =
|
||||
"\nWarning: 'Solve Tangents' required when using a Normal Map!\n\nPlease\n"
|
||||
+ "a) enable 'Solve Tangents' at the SkeletonRenderer/SkeletonAnimation component under 'Advanced' or\n"
|
||||
+ "b) clear the 'Normal Map' parameter at the Material.\n";
|
||||
public static readonly string kNoSkeletonGraphicMaterialMessage =
|
||||
"\nWarning: Normal non-UI shaders other than 'Spine/SkeletonGraphic *' are not compatible with 'SkeletonGraphic' components! "
|
||||
+ "This will lead to incorrect rendering on some devices.\n\n"
|
||||
+ "Please change the assigned Material to e.g. 'SkeletonGraphicDefault' or change the used shader to one of the 'Spine/SkeletonGraphic *' shaders.\n\n"
|
||||
+ "Note that 'Spine/SkeletonGraphic *' shall still be used when using URP.\n";
|
||||
public static readonly string kNoSkeletonGraphicTintBlackMaterialMessage =
|
||||
"\nWarning: Only enable 'Canvas Group Tint Black' when using a 'SkeletonGraphic Tint Black' shader!\n"
|
||||
+ "This will lead to incorrect rendering.\n\nPlease\n"
|
||||
+ "a) disable 'Canvas Group Tint Black' under 'Advanced' or\n"
|
||||
+ "b) use a 'SkeletonGraphic Tint Black' Material if you need Tint Black on a CanvasGroup.\n";
|
||||
|
||||
public static readonly string kTintBlackMessage =
|
||||
"\nWarning: 'Advanced - Tint Black' required when using any 'Tint Black' shader!\n\nPlease\n"
|
||||
+ "a) enable 'Tint Black' at the SkeletonRenderer/SkeletonGraphic component under 'Advanced' or\n"
|
||||
+ "b) use a different shader at the Material.\n";
|
||||
public static readonly string kCanvasTintBlackMessage =
|
||||
"\nWarning: Canvas 'Additional Shader Channels' 'uv1' and 'uv2' are required when 'Advanced - Tint Black' is enabled!\n\n"
|
||||
+ "Please enable both 'uv1' and 'uv2' channels at the parent Canvas component parameter 'Additional Shader Channels'.\n";
|
||||
public static readonly string kCanvasGroupCompatibleMessage =
|
||||
"\nWarning: 'Canvas Group Tint Black' is enabled at SkeletonGraphic but not 'CanvasGroup Compatible' at the Material!\n\nPlease\n"
|
||||
+ "a) enable 'CanvasGroup Compatible' at the Material or\n"
|
||||
+ "b) disable 'Canvas Group Tint Black' at the SkeletonGraphic component under 'Advanced'.\n"
|
||||
+ "You may want to duplicate the 'SkeletonGraphicDefault' material and change settings at the duplicate to not affect all instances.";
|
||||
|
||||
public static bool IsMaterialSetupProblematic (SkeletonRenderer renderer, ref string errorMessage) {
|
||||
var materials = renderer.GetComponent<Renderer>().sharedMaterials;
|
||||
bool isProblematic = false;
|
||||
foreach (var material in materials) {
|
||||
if (material == null) continue;
|
||||
isProblematic |= IsMaterialSetupProblematic(material, ref errorMessage);
|
||||
if (renderer.zSpacing == 0) {
|
||||
isProblematic |= IsZSpacingRequired(material, ref errorMessage);
|
||||
}
|
||||
if (renderer.addNormals == false && RequiresMeshNormals(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kAddNormalsMessage;
|
||||
}
|
||||
if (renderer.calculateTangents == false && RequiresTangents(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kSolveTangentsMessage;
|
||||
}
|
||||
if (renderer.tintBlack == false && RequiresTintBlack(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kTintBlackMessage;
|
||||
}
|
||||
}
|
||||
return isProblematic;
|
||||
}
|
||||
|
||||
public static bool IsMaterialSetupProblematic(SkeletonGraphic skeletonGraphic, ref string errorMessage)
|
||||
{
|
||||
var material = skeletonGraphic.material;
|
||||
bool isProblematic = false;
|
||||
if (material) {
|
||||
isProblematic |= IsMaterialSetupProblematic(material, ref errorMessage);
|
||||
var settings = skeletonGraphic.MeshGenerator.settings;
|
||||
if (settings.zSpacing == 0) {
|
||||
isProblematic |= IsZSpacingRequired(material, ref errorMessage);
|
||||
}
|
||||
if (IsSpineNonSkeletonGraphicMaterial(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kNoSkeletonGraphicMaterialMessage;
|
||||
}
|
||||
if (settings.tintBlack == false && RequiresTintBlack(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kTintBlackMessage;
|
||||
}
|
||||
if (settings.tintBlack == true && CanvasNotSetupForTintBlack(skeletonGraphic)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kCanvasTintBlackMessage;
|
||||
}
|
||||
if (settings.canvasGroupTintBlack == true && !IsSkeletonGraphicTintBlackMaterial(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kNoSkeletonGraphicTintBlackMaterialMessage;
|
||||
}
|
||||
if (settings.canvasGroupTintBlack == true && !IsCanvasGroupCompatible(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kCanvasGroupCompatibleMessage;
|
||||
}
|
||||
}
|
||||
return isProblematic;
|
||||
}
|
||||
|
||||
public static bool IsMaterialSetupProblematic(Material material, ref string errorMessage) {
|
||||
return !IsColorSpaceSupported(material, ref errorMessage);
|
||||
}
|
||||
|
||||
public static bool IsZSpacingRequired(Material material, ref string errorMessage) {
|
||||
bool hasForwardAddPass = material.FindPass("FORWARD_DELTA") >= 0;
|
||||
if (hasForwardAddPass) {
|
||||
errorMessage += kZSpacingRequiredMessage;
|
||||
return true;
|
||||
}
|
||||
bool zWrite = material.HasProperty("_ZWrite") && material.GetFloat("_ZWrite") > 0.0f;
|
||||
if (zWrite) {
|
||||
errorMessage += kZSpacingRecommendedMessage;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool IsColorSpaceSupported (Material material, ref string errorMessage) {
|
||||
if (QualitySettings.activeColorSpace == ColorSpace.Linear) {
|
||||
if (IsPMAMaterial(material)) {
|
||||
errorMessage += kPMANotSupportedLinearMessage;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public static bool UsesSpineShader (Material material) {
|
||||
return material.shader.name.Contains("Spine/");
|
||||
}
|
||||
|
||||
public static bool IsTextureSetupProblematic (Material material, ColorSpace colorSpace,
|
||||
bool sRGBTexture, bool mipmapEnabled, bool alphaIsTransparency,
|
||||
string texturePath, string materialPath,
|
||||
ref string errorMessage) {
|
||||
|
||||
if (material == null || !UsesSpineShader(material)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool isProblematic = false;
|
||||
if (IsPMAMaterial(material)) {
|
||||
// 'sRGBTexture = true' generates incorrectly weighted mipmaps at PMA textures,
|
||||
// causing white borders due to undesired custom weighting.
|
||||
if (sRGBTexture && mipmapEnabled && colorSpace == ColorSpace.Gamma) {
|
||||
errorMessage += string.Format("`{0}` : Problematic Texture Settings found: " +
|
||||
"When enabling `Generate Mip Maps` in Gamma color space, it is recommended " +
|
||||
"to disable `sRGB (Color Texture)` on `Premultiply alpha` textures. Otherwise " +
|
||||
"you will receive white border artifacts on an atlas exported with default " +
|
||||
"`Premultiply alpha` settings.\n" +
|
||||
"(You can disable this warning in `Edit - Preferences - Spine`)\n", texturePath);
|
||||
isProblematic = true;
|
||||
}
|
||||
if (alphaIsTransparency) {
|
||||
string materialName = System.IO.Path.GetFileName(materialPath);
|
||||
errorMessage += string.Format("`{0}` and material `{1}` : Problematic " +
|
||||
"Texture / Material Settings found: It is recommended to disable " +
|
||||
"`Alpha Is Transparency` on `Premultiply alpha` textures.\n" +
|
||||
"Assuming `Premultiply alpha` texture because `Straight Alpha Texture` " +
|
||||
"is disabled at material). " +
|
||||
"(You can disable this warning in `Edit - Preferences - Spine`)\n", texturePath, materialName);
|
||||
isProblematic = true;
|
||||
}
|
||||
}
|
||||
else { // straight alpha texture
|
||||
if (!alphaIsTransparency) {
|
||||
string materialName = System.IO.Path.GetFileName(materialPath);
|
||||
errorMessage += string.Format("`{0}` and material `{1}` : Incorrect" +
|
||||
"Texture / Material Settings found: It is strongly recommended " +
|
||||
"to enable `Alpha Is Transparency` on `Straight alpha` textures.\n" +
|
||||
"Assuming `Straight alpha` texture because `Straight Alpha Texture` " +
|
||||
"is enabled at material). " +
|
||||
"(You can disable this warning in `Edit - Preferences - Spine`)\n", texturePath, materialName);
|
||||
isProblematic = true;
|
||||
}
|
||||
}
|
||||
return isProblematic;
|
||||
}
|
||||
|
||||
public static void EnablePMAAtMaterial (Material material, bool enablePMA) {
|
||||
if (material.HasProperty(STRAIGHT_ALPHA_PARAM_ID)) {
|
||||
material.SetInt(STRAIGHT_ALPHA_PARAM_ID, enablePMA ? 0 : 1);
|
||||
if (enablePMA)
|
||||
material.DisableKeyword(STRAIGHT_ALPHA_KEYWORD);
|
||||
else
|
||||
material.EnableKeyword(STRAIGHT_ALPHA_KEYWORD);
|
||||
}
|
||||
else {
|
||||
if (enablePMA)
|
||||
material.EnableKeyword(ALPHAPREMULTIPLY_ON_KEYWORD);
|
||||
else
|
||||
material.DisableKeyword(ALPHAPREMULTIPLY_ON_KEYWORD);
|
||||
}
|
||||
}
|
||||
|
||||
static bool IsPMAMaterial (Material material) {
|
||||
bool usesAlphaPremultiplyKeyword = IsSpriteShader(material);
|
||||
if (usesAlphaPremultiplyKeyword)
|
||||
return material.IsKeywordEnabled(ALPHAPREMULTIPLY_ON_KEYWORD);
|
||||
else
|
||||
return material.HasProperty(STRAIGHT_ALPHA_PARAM_ID) && material.GetInt(STRAIGHT_ALPHA_PARAM_ID) == 0;
|
||||
}
|
||||
|
||||
static bool IsURP3DMaterial (Material material) {
|
||||
return material.shader.name.Contains("Universal Render Pipeline/Spine");
|
||||
}
|
||||
|
||||
static bool IsSpineNonSkeletonGraphicMaterial (Material material) {
|
||||
return material.shader.name.Contains("Spine") && !material.shader.name.Contains("SkeletonGraphic");
|
||||
}
|
||||
|
||||
static bool IsSkeletonGraphicTintBlackMaterial (Material material) {
|
||||
return material.shader.name.Contains("Spine") && material.shader.name.Contains("SkeletonGraphic")
|
||||
&& material.shader.name.Contains("Black");
|
||||
}
|
||||
|
||||
static bool AreShadowsDisabled (Material material) {
|
||||
return material.IsKeywordEnabled("_RECEIVE_SHADOWS_OFF");
|
||||
}
|
||||
|
||||
static bool RequiresMeshNormals (Material material) {
|
||||
bool anyFixedNormalSet = false;
|
||||
foreach (string fixedNormalKeyword in FIXED_NORMALS_KEYWORDS) {
|
||||
if (material.IsKeywordEnabled(fixedNormalKeyword)) {
|
||||
anyFixedNormalSet = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
bool isShaderWithMeshNormals = IsSpriteShader(material);
|
||||
return isShaderWithMeshNormals && !anyFixedNormalSet;
|
||||
}
|
||||
|
||||
static bool IsSpriteShader (Material material) {
|
||||
string shaderName = material.shader.name;
|
||||
return shaderName.Contains("Spine/Sprite/Pixel Lit") ||
|
||||
shaderName.Contains("Spine/Sprite/Vertex Lit") ||
|
||||
shaderName.Contains("2D/Spine/Sprite") || // covers both URP and LWRP
|
||||
shaderName.Contains("Pipeline/Spine/Sprite"); // covers both URP and LWRP
|
||||
}
|
||||
|
||||
static bool RequiresTintBlack (Material material) {
|
||||
bool isTintBlackShader =
|
||||
material.shader.name.Contains("Spine") &&
|
||||
material.shader.name.Contains("Tint Black");
|
||||
return isTintBlackShader;
|
||||
}
|
||||
|
||||
static bool RequiresTangents (Material material) {
|
||||
return material.IsKeywordEnabled(NORMALMAP_KEYWORD);
|
||||
}
|
||||
static bool IsCanvasGroupCompatible (Material material) {
|
||||
return material.IsKeywordEnabled(CANVAS_GROUP_COMPATIBLE_KEYWORD);
|
||||
}
|
||||
|
||||
static bool CanvasNotSetupForTintBlack (SkeletonGraphic skeletonGraphic) {
|
||||
Canvas canvas = skeletonGraphic.canvas;
|
||||
if (!canvas)
|
||||
return false;
|
||||
var requiredChannels =
|
||||
AdditionalCanvasShaderChannels.TexCoord1 |
|
||||
AdditionalCanvasShaderChannels.TexCoord2;
|
||||
return (canvas.additionalShaderChannels & requiredChannels) != requiredChannels;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // UNITY_EDITOR
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e68fa8db689084946adce454b83e6d4a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,614 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated January 1, 2020. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2020, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software
|
||||
* or otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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
|
||||
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using UnityEngine;
|
||||
|
||||
namespace Spine.Unity {
|
||||
public static class SkeletonExtensions {
|
||||
|
||||
#region Colors
|
||||
const float ByteToFloat = 1f / 255f;
|
||||
public static Color GetColor (this Skeleton s) { return new Color(s.r, s.g, s.b, s.a); }
|
||||
public static Color GetColor (this RegionAttachment a) { return new Color(a.r, a.g, a.b, a.a); }
|
||||
public static Color GetColor (this MeshAttachment a) { return new Color(a.r, a.g, a.b, a.a); }
|
||||
public static Color GetColor (this Slot s) { return new Color(s.r, s.g, s.b, s.a); }
|
||||
public static Color GetColorTintBlack (this Slot s) { return new Color(s.r2, s.g2, s.b2, 1f); }
|
||||
|
||||
public static void SetColor (this Skeleton skeleton, Color color) {
|
||||
skeleton.A = color.a;
|
||||
skeleton.R = color.r;
|
||||
skeleton.G = color.g;
|
||||
skeleton.B = color.b;
|
||||
}
|
||||
|
||||
public static void SetColor (this Skeleton skeleton, Color32 color) {
|
||||
skeleton.A = color.a * ByteToFloat;
|
||||
skeleton.R = color.r * ByteToFloat;
|
||||
skeleton.G = color.g * ByteToFloat;
|
||||
skeleton.B = color.b * ByteToFloat;
|
||||
}
|
||||
|
||||
public static void SetColor (this Slot slot, Color color) {
|
||||
slot.A = color.a;
|
||||
slot.R = color.r;
|
||||
slot.G = color.g;
|
||||
slot.B = color.b;
|
||||
}
|
||||
|
||||
public static void SetColor (this Slot slot, Color32 color) {
|
||||
slot.A = color.a * ByteToFloat;
|
||||
slot.R = color.r * ByteToFloat;
|
||||
slot.G = color.g * ByteToFloat;
|
||||
slot.B = color.b * ByteToFloat;
|
||||
}
|
||||
|
||||
public static void SetColor (this RegionAttachment attachment, Color color) {
|
||||
attachment.A = color.a;
|
||||
attachment.R = color.r;
|
||||
attachment.G = color.g;
|
||||
attachment.B = color.b;
|
||||
}
|
||||
|
||||
public static void SetColor (this RegionAttachment attachment, Color32 color) {
|
||||
attachment.A = color.a * ByteToFloat;
|
||||
attachment.R = color.r * ByteToFloat;
|
||||
attachment.G = color.g * ByteToFloat;
|
||||
attachment.B = color.b * ByteToFloat;
|
||||
}
|
||||
|
||||
public static void SetColor (this MeshAttachment attachment, Color color) {
|
||||
attachment.A = color.a;
|
||||
attachment.R = color.r;
|
||||
attachment.G = color.g;
|
||||
attachment.B = color.b;
|
||||
}
|
||||
|
||||
public static void SetColor (this MeshAttachment attachment, Color32 color) {
|
||||
attachment.A = color.a * ByteToFloat;
|
||||
attachment.R = color.r * ByteToFloat;
|
||||
attachment.G = color.g * ByteToFloat;
|
||||
attachment.B = color.b * ByteToFloat;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Skeleton
|
||||
/// <summary>Sets the Skeleton's local scale using a UnityEngine.Vector2. If only individual components need to be set, set Skeleton.ScaleX or Skeleton.ScaleY.</summary>
|
||||
public static void SetLocalScale (this Skeleton skeleton, Vector2 scale) {
|
||||
skeleton.ScaleX = scale.x;
|
||||
skeleton.ScaleY = scale.y;
|
||||
}
|
||||
|
||||
/// <summary>Gets the internal bone matrix as a Unity bonespace-to-skeletonspace transformation matrix.</summary>
|
||||
public static Matrix4x4 GetMatrix4x4 (this Bone bone) {
|
||||
return new Matrix4x4 {
|
||||
m00 = bone.a,
|
||||
m01 = bone.b,
|
||||
m03 = bone.worldX,
|
||||
m10 = bone.c,
|
||||
m11 = bone.d,
|
||||
m13 = bone.worldY,
|
||||
m33 = 1
|
||||
};
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Bone
|
||||
/// <summary>Sets the bone's (local) X and Y according to a Vector2</summary>
|
||||
public static void SetLocalPosition (this Bone bone, Vector2 position) {
|
||||
bone.X = position.x;
|
||||
bone.Y = position.y;
|
||||
}
|
||||
|
||||
/// <summary>Sets the bone's (local) X and Y according to a Vector3. The z component is ignored.</summary>
|
||||
public static void SetLocalPosition (this Bone bone, Vector3 position) {
|
||||
bone.X = position.x;
|
||||
bone.Y = position.y;
|
||||
}
|
||||
|
||||
/// <summary>Gets the bone's local X and Y as a Vector2.</summary>
|
||||
public static Vector2 GetLocalPosition (this Bone bone) {
|
||||
return new Vector2(bone.x, bone.y);
|
||||
}
|
||||
|
||||
/// <summary>Gets the position of the bone in Skeleton-space.</summary>
|
||||
public static Vector2 GetSkeletonSpacePosition (this Bone bone) {
|
||||
return new Vector2(bone.worldX, bone.worldY);
|
||||
}
|
||||
|
||||
/// <summary>Gets a local offset from the bone and converts it into Skeleton-space.</summary>
|
||||
public static Vector2 GetSkeletonSpacePosition (this Bone bone, Vector2 boneLocal) {
|
||||
Vector2 o;
|
||||
bone.LocalToWorld(boneLocal.x, boneLocal.y, out o.x, out o.y);
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>Gets the bone's Unity World position using its Spine GameObject Transform. UpdateWorldTransform needs to have been called for this to return the correct, updated value.</summary>
|
||||
public static Vector3 GetWorldPosition (this Bone bone, UnityEngine.Transform spineGameObjectTransform) {
|
||||
return spineGameObjectTransform.TransformPoint(new Vector3(bone.worldX, bone.worldY));
|
||||
}
|
||||
|
||||
public static Vector3 GetWorldPosition (this Bone bone, UnityEngine.Transform spineGameObjectTransform, float positionScale) {
|
||||
return spineGameObjectTransform.TransformPoint(new Vector3(bone.worldX * positionScale, bone.worldY * positionScale));
|
||||
}
|
||||
|
||||
/// <summary>Gets a skeleton space UnityEngine.Quaternion representation of bone.WorldRotationX.</summary>
|
||||
public static Quaternion GetQuaternion (this Bone bone) {
|
||||
var halfRotation = Mathf.Atan2(bone.c, bone.a) * 0.5f;
|
||||
return new Quaternion(0, 0, Mathf.Sin(halfRotation), Mathf.Cos(halfRotation));
|
||||
}
|
||||
|
||||
/// <summary>Gets a bone-local space UnityEngine.Quaternion representation of bone.rotation.</summary>
|
||||
public static Quaternion GetLocalQuaternion (this Bone bone) {
|
||||
var halfRotation = bone.rotation * Mathf.Deg2Rad * 0.5f;
|
||||
return new Quaternion(0, 0, Mathf.Sin(halfRotation), Mathf.Cos(halfRotation));
|
||||
}
|
||||
|
||||
/// <summary>Returns the Skeleton's local scale as a UnityEngine.Vector2. If only individual components are needed, use Skeleton.ScaleX or Skeleton.ScaleY.</summary>
|
||||
public static Vector2 GetLocalScale (this Skeleton skeleton) {
|
||||
return new Vector2(skeleton.ScaleX, skeleton.ScaleY);
|
||||
}
|
||||
|
||||
/// <summary>Calculates a 2x2 Transformation Matrix that can convert a skeleton-space position to a bone-local position.</summary>
|
||||
public static void GetWorldToLocalMatrix (this Bone bone, out float ia, out float ib, out float ic, out float id) {
|
||||
float a = bone.a, b = bone.b, c = bone.c, d = bone.d;
|
||||
float invDet = 1 / (a * d - b * c);
|
||||
ia = invDet * d;
|
||||
ib = invDet * -b;
|
||||
ic = invDet * -c;
|
||||
id = invDet * a;
|
||||
}
|
||||
|
||||
/// <summary>UnityEngine.Vector2 override of Bone.WorldToLocal. This converts a skeleton-space position into a bone local position.</summary>
|
||||
public static Vector2 WorldToLocal (this Bone bone, Vector2 worldPosition) {
|
||||
Vector2 o;
|
||||
bone.WorldToLocal(worldPosition.x, worldPosition.y, out o.x, out o.y);
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>Sets the skeleton-space position of a bone.</summary>
|
||||
/// <returns>The local position in its parent bone space, or in skeleton space if it is the root bone.</returns>
|
||||
public static Vector2 SetPositionSkeletonSpace (this Bone bone, Vector2 skeletonSpacePosition) {
|
||||
if (bone.parent == null) { // root bone
|
||||
bone.SetLocalPosition(skeletonSpacePosition);
|
||||
return skeletonSpacePosition;
|
||||
} else {
|
||||
var parent = bone.parent;
|
||||
Vector2 parentLocal = parent.WorldToLocal(skeletonSpacePosition);
|
||||
bone.SetLocalPosition(parentLocal);
|
||||
return parentLocal;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Attachments
|
||||
public static Material GetMaterial (this Attachment a) {
|
||||
object rendererObject = null;
|
||||
var renderableAttachment = a as IHasRendererObject;
|
||||
if (renderableAttachment != null)
|
||||
rendererObject = renderableAttachment.RendererObject;
|
||||
|
||||
if (rendererObject == null)
|
||||
return null;
|
||||
|
||||
#if SPINE_TK2D
|
||||
return (rendererObject.GetType() == typeof(Material)) ? (Material)rendererObject : (Material)((AtlasRegion)rendererObject).page.rendererObject;
|
||||
#else
|
||||
return (Material)((AtlasRegion)rendererObject).page.rendererObject;
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>Fills a Vector2 buffer with local vertices.</summary>
|
||||
/// <param name="va">The VertexAttachment</param>
|
||||
/// <param name="slot">Slot where the attachment belongs.</param>
|
||||
/// <param name="buffer">Correctly-sized buffer. Use attachment's .WorldVerticesLength to get the correct size. If null, a new Vector2[] of the correct size will be allocated.</param>
|
||||
public static Vector2[] GetLocalVertices (this VertexAttachment va, Slot slot, Vector2[] buffer) {
|
||||
int floatsCount = va.worldVerticesLength;
|
||||
int bufferTargetSize = floatsCount >> 1;
|
||||
buffer = buffer ?? new Vector2[bufferTargetSize];
|
||||
if (buffer.Length < bufferTargetSize) throw new System.ArgumentException(string.Format("Vector2 buffer too small. {0} requires an array of size {1}. Use the attachment's .WorldVerticesLength to get the correct size.", va.Name, floatsCount), "buffer");
|
||||
|
||||
if (va.bones == null) {
|
||||
var localVerts = va.vertices;
|
||||
for (int i = 0; i < bufferTargetSize; i++) {
|
||||
int j = i * 2;
|
||||
buffer[i] = new Vector2(localVerts[j], localVerts[j+1]);
|
||||
}
|
||||
} else {
|
||||
var floats = new float[floatsCount];
|
||||
va.ComputeWorldVertices(slot, floats);
|
||||
|
||||
Bone sb = slot.bone;
|
||||
float ia, ib, ic, id, bwx = sb.worldX, bwy = sb.worldY;
|
||||
sb.GetWorldToLocalMatrix(out ia, out ib, out ic, out id);
|
||||
|
||||
for (int i = 0; i < bufferTargetSize; i++) {
|
||||
int j = i * 2;
|
||||
float x = floats[j] - bwx, y = floats[j+1] - bwy;
|
||||
buffer[i] = new Vector2(x * ia + y * ib, x * ic + y * id);
|
||||
}
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/// <summary>Calculates world vertices and fills a Vector2 buffer.</summary>
|
||||
/// <param name="a">The VertexAttachment</param>
|
||||
/// <param name="slot">Slot where the attachment belongs.</param>
|
||||
/// <param name="buffer">Correctly-sized buffer. Use attachment's .WorldVerticesLength to get the correct size. If null, a new Vector2[] of the correct size will be allocated.</param>
|
||||
public static Vector2[] GetWorldVertices (this VertexAttachment a, Slot slot, Vector2[] buffer) {
|
||||
int worldVertsLength = a.worldVerticesLength;
|
||||
int bufferTargetSize = worldVertsLength >> 1;
|
||||
buffer = buffer ?? new Vector2[bufferTargetSize];
|
||||
if (buffer.Length < bufferTargetSize) throw new System.ArgumentException(string.Format("Vector2 buffer too small. {0} requires an array of size {1}. Use the attachment's .WorldVerticesLength to get the correct size.", a.Name, worldVertsLength), "buffer");
|
||||
|
||||
var floats = new float[worldVertsLength];
|
||||
a.ComputeWorldVertices(slot, floats);
|
||||
|
||||
for (int i = 0, n = worldVertsLength >> 1; i < n; i++) {
|
||||
int j = i * 2;
|
||||
buffer[i] = new Vector2(floats[j], floats[j + 1]);
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/// <summary>Gets the PointAttachment's Unity World position using its Spine GameObject Transform.</summary>
|
||||
public static Vector3 GetWorldPosition (this PointAttachment attachment, Slot slot, Transform spineGameObjectTransform) {
|
||||
Vector3 skeletonSpacePosition;
|
||||
skeletonSpacePosition.z = 0;
|
||||
attachment.ComputeWorldPosition(slot.bone, out skeletonSpacePosition.x, out skeletonSpacePosition.y);
|
||||
return spineGameObjectTransform.TransformPoint(skeletonSpacePosition);
|
||||
}
|
||||
|
||||
/// <summary>Gets the PointAttachment's Unity World position using its Spine GameObject Transform.</summary>
|
||||
public static Vector3 GetWorldPosition (this PointAttachment attachment, Bone bone, Transform spineGameObjectTransform) {
|
||||
Vector3 skeletonSpacePosition;
|
||||
skeletonSpacePosition.z = 0;
|
||||
attachment.ComputeWorldPosition(bone, out skeletonSpacePosition.x, out skeletonSpacePosition.y);
|
||||
return spineGameObjectTransform.TransformPoint(skeletonSpacePosition);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
namespace Spine {
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
public struct BoneMatrix {
|
||||
public float a, b, c, d, x, y;
|
||||
|
||||
/// <summary>Recursively calculates a worldspace bone matrix based on BoneData.</summary>
|
||||
public static BoneMatrix CalculateSetupWorld (BoneData boneData) {
|
||||
if (boneData == null)
|
||||
return default(BoneMatrix);
|
||||
|
||||
// End condition: isRootBone
|
||||
if (boneData.parent == null)
|
||||
return GetInheritedInternal(boneData, default(BoneMatrix));
|
||||
|
||||
BoneMatrix result = CalculateSetupWorld(boneData.parent);
|
||||
return GetInheritedInternal(boneData, result);
|
||||
}
|
||||
|
||||
static BoneMatrix GetInheritedInternal (BoneData boneData, BoneMatrix parentMatrix) {
|
||||
var parent = boneData.parent;
|
||||
if (parent == null) return new BoneMatrix(boneData); // isRootBone
|
||||
|
||||
float pa = parentMatrix.a, pb = parentMatrix.b, pc = parentMatrix.c, pd = parentMatrix.d;
|
||||
BoneMatrix result = default(BoneMatrix);
|
||||
result.x = pa * boneData.x + pb * boneData.y + parentMatrix.x;
|
||||
result.y = pc * boneData.x + pd * boneData.y + parentMatrix.y;
|
||||
|
||||
switch (boneData.transformMode) {
|
||||
case TransformMode.Normal: {
|
||||
float rotationY = boneData.rotation + 90 + boneData.shearY;
|
||||
float la = MathUtils.CosDeg(boneData.rotation + boneData.shearX) * boneData.scaleX;
|
||||
float lb = MathUtils.CosDeg(rotationY) * boneData.scaleY;
|
||||
float lc = MathUtils.SinDeg(boneData.rotation + boneData.shearX) * boneData.scaleX;
|
||||
float ld = MathUtils.SinDeg(rotationY) * boneData.scaleY;
|
||||
result.a = pa * la + pb * lc;
|
||||
result.b = pa * lb + pb * ld;
|
||||
result.c = pc * la + pd * lc;
|
||||
result.d = pc * lb + pd * ld;
|
||||
break;
|
||||
}
|
||||
case TransformMode.OnlyTranslation: {
|
||||
float rotationY = boneData.rotation + 90 + boneData.shearY;
|
||||
result.a = MathUtils.CosDeg(boneData.rotation + boneData.shearX) * boneData.scaleX;
|
||||
result.b = MathUtils.CosDeg(rotationY) * boneData.scaleY;
|
||||
result.c = MathUtils.SinDeg(boneData.rotation + boneData.shearX) * boneData.scaleX;
|
||||
result.d = MathUtils.SinDeg(rotationY) * boneData.scaleY;
|
||||
break;
|
||||
}
|
||||
case TransformMode.NoRotationOrReflection: {
|
||||
float s = pa * pa + pc * pc, prx;
|
||||
if (s > 0.0001f) {
|
||||
s = Math.Abs(pa * pd - pb * pc) / s;
|
||||
pb = pc * s;
|
||||
pd = pa * s;
|
||||
prx = MathUtils.Atan2(pc, pa) * MathUtils.RadDeg;
|
||||
} else {
|
||||
pa = 0;
|
||||
pc = 0;
|
||||
prx = 90 - MathUtils.Atan2(pd, pb) * MathUtils.RadDeg;
|
||||
}
|
||||
float rx = boneData.rotation + boneData.shearX - prx;
|
||||
float ry = boneData.rotation + boneData.shearY - prx + 90;
|
||||
float la = MathUtils.CosDeg(rx) * boneData.scaleX;
|
||||
float lb = MathUtils.CosDeg(ry) * boneData.scaleY;
|
||||
float lc = MathUtils.SinDeg(rx) * boneData.scaleX;
|
||||
float ld = MathUtils.SinDeg(ry) * boneData.scaleY;
|
||||
result.a = pa * la - pb * lc;
|
||||
result.b = pa * lb - pb * ld;
|
||||
result.c = pc * la + pd * lc;
|
||||
result.d = pc * lb + pd * ld;
|
||||
break;
|
||||
}
|
||||
case TransformMode.NoScale:
|
||||
case TransformMode.NoScaleOrReflection: {
|
||||
float cos = MathUtils.CosDeg(boneData.rotation), sin = MathUtils.SinDeg(boneData.rotation);
|
||||
float za = pa * cos + pb * sin;
|
||||
float zc = pc * cos + pd * sin;
|
||||
float s = (float)Math.Sqrt(za * za + zc * zc);
|
||||
if (s > 0.00001f)
|
||||
s = 1 / s;
|
||||
za *= s;
|
||||
zc *= s;
|
||||
s = (float)Math.Sqrt(za * za + zc * zc);
|
||||
float r = MathUtils.PI / 2 + MathUtils.Atan2(zc, za);
|
||||
float zb = MathUtils.Cos(r) * s;
|
||||
float zd = MathUtils.Sin(r) * s;
|
||||
float la = MathUtils.CosDeg(boneData.shearX) * boneData.scaleX;
|
||||
float lb = MathUtils.CosDeg(90 + boneData.shearY) * boneData.scaleY;
|
||||
float lc = MathUtils.SinDeg(boneData.shearX) * boneData.scaleX;
|
||||
float ld = MathUtils.SinDeg(90 + boneData.shearY) * boneData.scaleY;
|
||||
if (boneData.transformMode != TransformMode.NoScaleOrReflection ? pa * pd - pb * pc < 0 : false) {
|
||||
zb = -zb;
|
||||
zd = -zd;
|
||||
}
|
||||
result.a = za * la + zb * lc;
|
||||
result.b = za * lb + zb * ld;
|
||||
result.c = zc * la + zd * lc;
|
||||
result.d = zc * lb + zd * ld;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Constructor for a local bone matrix based on Setup Pose BoneData.</summary>
|
||||
public BoneMatrix (BoneData boneData) {
|
||||
float rotationY = boneData.rotation + 90 + boneData.shearY;
|
||||
float rotationX = boneData.rotation + boneData.shearX;
|
||||
|
||||
a = MathUtils.CosDeg(rotationX) * boneData.scaleX;
|
||||
c = MathUtils.SinDeg(rotationX) * boneData.scaleX;
|
||||
b = MathUtils.CosDeg(rotationY) * boneData.scaleY;
|
||||
d = MathUtils.SinDeg(rotationY) * boneData.scaleY;
|
||||
x = boneData.x;
|
||||
y = boneData.y;
|
||||
}
|
||||
|
||||
/// <summary>Constructor for a local bone matrix based on a bone instance's current pose.</summary>
|
||||
public BoneMatrix (Bone bone) {
|
||||
float rotationY = bone.rotation + 90 + bone.shearY;
|
||||
float rotationX = bone.rotation + bone.shearX;
|
||||
|
||||
a = MathUtils.CosDeg(rotationX) * bone.scaleX;
|
||||
c = MathUtils.SinDeg(rotationX) * bone.scaleX;
|
||||
b = MathUtils.CosDeg(rotationY) * bone.scaleY;
|
||||
d = MathUtils.SinDeg(rotationY) * bone.scaleY;
|
||||
x = bone.x;
|
||||
y = bone.y;
|
||||
}
|
||||
|
||||
public BoneMatrix TransformMatrix (BoneMatrix local) {
|
||||
return new BoneMatrix {
|
||||
a = this.a * local.a + this.b * local.c,
|
||||
b = this.a * local.b + this.b * local.d,
|
||||
c = this.c * local.a + this.d * local.c,
|
||||
d = this.c * local.b + this.d * local.d,
|
||||
x = this.a * local.x + this.b * local.y + this.x,
|
||||
y = this.c * local.x + this.d * local.y + this.y
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public static class SpineSkeletonExtensions {
|
||||
public static bool IsWeighted (this VertexAttachment va) {
|
||||
return va.bones != null && va.bones.Length > 0;
|
||||
}
|
||||
|
||||
public static bool IsRenderable (this Attachment a) {
|
||||
return a is IHasRendererObject;
|
||||
}
|
||||
|
||||
#region Transform Modes
|
||||
public static bool InheritsRotation (this TransformMode mode) {
|
||||
const int RotationBit = 0;
|
||||
return ((int)mode & (1U << RotationBit)) == 0;
|
||||
}
|
||||
|
||||
public static bool InheritsScale (this TransformMode mode) {
|
||||
const int ScaleBit = 1;
|
||||
return ((int)mode & (1U << ScaleBit)) == 0;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Posing
|
||||
internal static void SetPropertyToSetupPose (this Skeleton skeleton, int propertyID) {
|
||||
int tt = propertyID >> 24;
|
||||
var timelineType = (TimelineType)tt;
|
||||
int i = propertyID - (tt << 24);
|
||||
|
||||
Bone bone;
|
||||
IkConstraint ikc;
|
||||
PathConstraint pc;
|
||||
|
||||
switch (timelineType) {
|
||||
// Bone
|
||||
case TimelineType.Rotate:
|
||||
bone = skeleton.bones.Items[i];
|
||||
bone.rotation = bone.data.rotation;
|
||||
break;
|
||||
case TimelineType.Translate:
|
||||
bone = skeleton.bones.Items[i];
|
||||
bone.x = bone.data.x;
|
||||
bone.y = bone.data.y;
|
||||
break;
|
||||
case TimelineType.Scale:
|
||||
bone = skeleton.bones.Items[i];
|
||||
bone.scaleX = bone.data.scaleX;
|
||||
bone.scaleY = bone.data.scaleY;
|
||||
break;
|
||||
case TimelineType.Shear:
|
||||
bone = skeleton.bones.Items[i];
|
||||
bone.shearX = bone.data.shearX;
|
||||
bone.shearY = bone.data.shearY;
|
||||
break;
|
||||
|
||||
// Slot
|
||||
case TimelineType.Attachment:
|
||||
skeleton.SetSlotAttachmentToSetupPose(i);
|
||||
break;
|
||||
case TimelineType.Color:
|
||||
skeleton.slots.Items[i].SetColorToSetupPose();
|
||||
break;
|
||||
case TimelineType.TwoColor:
|
||||
skeleton.slots.Items[i].SetColorToSetupPose();
|
||||
break;
|
||||
case TimelineType.Deform:
|
||||
skeleton.slots.Items[i].Deform.Clear();
|
||||
break;
|
||||
|
||||
// Skeleton
|
||||
case TimelineType.DrawOrder:
|
||||
skeleton.SetDrawOrderToSetupPose();
|
||||
break;
|
||||
|
||||
// IK Constraint
|
||||
case TimelineType.IkConstraint:
|
||||
ikc = skeleton.ikConstraints.Items[i];
|
||||
ikc.mix = ikc.data.mix;
|
||||
ikc.softness = ikc.data.softness;
|
||||
ikc.bendDirection = ikc.data.bendDirection;
|
||||
ikc.stretch = ikc.data.stretch;
|
||||
break;
|
||||
|
||||
// TransformConstraint
|
||||
case TimelineType.TransformConstraint:
|
||||
var tc = skeleton.transformConstraints.Items[i];
|
||||
var tcData = tc.data;
|
||||
tc.rotateMix = tcData.rotateMix;
|
||||
tc.translateMix = tcData.translateMix;
|
||||
tc.scaleMix = tcData.scaleMix;
|
||||
tc.shearMix = tcData.shearMix;
|
||||
break;
|
||||
|
||||
// Path Constraint
|
||||
case TimelineType.PathConstraintPosition:
|
||||
pc = skeleton.pathConstraints.Items[i];
|
||||
pc.position = pc.data.position;
|
||||
break;
|
||||
case TimelineType.PathConstraintSpacing:
|
||||
pc = skeleton.pathConstraints.Items[i];
|
||||
pc.spacing = pc.data.spacing;
|
||||
break;
|
||||
case TimelineType.PathConstraintMix:
|
||||
pc = skeleton.pathConstraints.Items[i];
|
||||
pc.rotateMix = pc.data.rotateMix;
|
||||
pc.translateMix = pc.data.translateMix;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Resets the DrawOrder to the Setup Pose's draw order</summary>
|
||||
public static void SetDrawOrderToSetupPose (this Skeleton skeleton) {
|
||||
var slotsItems = skeleton.slots.Items;
|
||||
int n = skeleton.slots.Count;
|
||||
|
||||
var drawOrder = skeleton.drawOrder;
|
||||
drawOrder.Clear(false);
|
||||
drawOrder.EnsureCapacity(n);
|
||||
drawOrder.Count = n;
|
||||
System.Array.Copy(slotsItems, drawOrder.Items, n);
|
||||
}
|
||||
|
||||
/// <summary>Resets all the slots on the skeleton to their Setup Pose attachments but does not reset slot colors.</summary>
|
||||
public static void SetSlotAttachmentsToSetupPose (this Skeleton skeleton) {
|
||||
var slotsItems = skeleton.slots.Items;
|
||||
for (int i = 0; i < skeleton.slots.Count; i++) {
|
||||
Slot slot = slotsItems[i];
|
||||
string attachmentName = slot.data.attachmentName;
|
||||
slot.Attachment = string.IsNullOrEmpty(attachmentName) ? null : skeleton.GetAttachment(i, attachmentName);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Resets the color of a slot to Setup Pose value.</summary>
|
||||
public static void SetColorToSetupPose (this Slot slot) {
|
||||
slot.r = slot.data.r;
|
||||
slot.g = slot.data.g;
|
||||
slot.b = slot.data.b;
|
||||
slot.a = slot.data.a;
|
||||
slot.r2 = slot.data.r2;
|
||||
slot.g2 = slot.data.g2;
|
||||
slot.b2 = slot.data.b2;
|
||||
}
|
||||
|
||||
/// <summary>Sets a slot's attachment to setup pose. If you have the slotIndex, Skeleton.SetSlotAttachmentToSetupPose is faster.</summary>
|
||||
public static void SetAttachmentToSetupPose (this Slot slot) {
|
||||
var slotData = slot.data;
|
||||
slot.Attachment = slot.bone.skeleton.GetAttachment(slotData.name, slotData.attachmentName);
|
||||
}
|
||||
|
||||
/// <summary>Resets the attachment of slot at a given slotIndex to setup pose. This is faster than Slot.SetAttachmentToSetupPose.</summary>
|
||||
public static void SetSlotAttachmentToSetupPose (this Skeleton skeleton, int slotIndex) {
|
||||
var slot = skeleton.slots.Items[slotIndex];
|
||||
string attachmentName = slot.data.attachmentName;
|
||||
if (string.IsNullOrEmpty(attachmentName)) {
|
||||
slot.Attachment = null;
|
||||
} else {
|
||||
var attachment = skeleton.GetAttachment(slotIndex, attachmentName);
|
||||
slot.Attachment = attachment;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Resets Skeleton parts to Setup Pose according to a Spine.Animation's keyed items.</summary>
|
||||
public static void SetKeyedItemsToSetupPose (this Animation animation, Skeleton skeleton) {
|
||||
animation.Apply(skeleton, 0, 0, false, null, 0, MixBlend.Setup, MixDirection.Out);
|
||||
}
|
||||
|
||||
public static void AllowImmediateQueue (this TrackEntry trackEntry) {
|
||||
if (trackEntry.nextTrackLast < 0) trackEntry.nextTrackLast = 0;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ea85c8f6a91a6ab45881b0dbdaabb7d0
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
@@ -0,0 +1,168 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated January 1, 2020. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2020, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software
|
||||
* or otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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
|
||||
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections;
|
||||
|
||||
namespace Spine.Unity.AttachmentTools {
|
||||
|
||||
public static class SkinUtilities {
|
||||
|
||||
#region Skeleton Skin Extensions
|
||||
/// <summary>
|
||||
/// Convenience method for duplicating a skeleton's current active skin so changes to it will not affect other skeleton instances. .</summary>
|
||||
public static Skin UnshareSkin (this Skeleton skeleton, bool includeDefaultSkin, bool unshareAttachments, AnimationState state = null) {
|
||||
// 1. Copy the current skin and set the skeleton's skin to the new one.
|
||||
var newSkin = skeleton.GetClonedSkin("cloned skin", includeDefaultSkin, unshareAttachments, true);
|
||||
skeleton.SetSkin(newSkin);
|
||||
|
||||
// 2. Apply correct attachments: skeleton.SetToSetupPose + animationState.Apply
|
||||
if (state != null) {
|
||||
skeleton.SetToSetupPose();
|
||||
state.Apply(skeleton);
|
||||
}
|
||||
|
||||
// 3. Return unshared skin.
|
||||
return newSkin;
|
||||
}
|
||||
|
||||
public static Skin GetClonedSkin (this Skeleton skeleton, string newSkinName, bool includeDefaultSkin = false, bool cloneAttachments = false, bool cloneMeshesAsLinked = true) {
|
||||
var newSkin = new Skin(newSkinName); // may have null name. Harmless.
|
||||
var defaultSkin = skeleton.data.DefaultSkin;
|
||||
var activeSkin = skeleton.skin;
|
||||
|
||||
if (includeDefaultSkin)
|
||||
defaultSkin.CopyTo(newSkin, true, cloneAttachments, cloneMeshesAsLinked);
|
||||
|
||||
if (activeSkin != null)
|
||||
activeSkin.CopyTo(newSkin, true, cloneAttachments, cloneMeshesAsLinked);
|
||||
|
||||
return newSkin;
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Gets a shallow copy of the skin. The cloned skin's attachments are shared with the original skin.</summary>
|
||||
public static Skin GetClone (this Skin original) {
|
||||
var newSkin = new Skin(original.name + " clone");
|
||||
var newSkinAttachments = newSkin.Attachments;
|
||||
var newSkinBones = newSkin.Bones;
|
||||
var newSkinConstraints = newSkin.Constraints;
|
||||
|
||||
foreach (var a in original.Attachments)
|
||||
newSkinAttachments[a.Key] = a.Value;
|
||||
|
||||
newSkinBones.AddRange(original.bones);
|
||||
newSkinConstraints.AddRange(original.constraints);
|
||||
return newSkin;
|
||||
}
|
||||
|
||||
/// <summary>Adds an attachment to the skin for the specified slot index and name. If the name already exists for the slot, the previous value is replaced.</summary>
|
||||
public static void SetAttachment (this Skin skin, string slotName, string keyName, Attachment attachment, Skeleton skeleton) {
|
||||
int slotIndex = skeleton.FindSlotIndex(slotName);
|
||||
if (skeleton == null) throw new System.ArgumentNullException("skeleton", "skeleton cannot be null.");
|
||||
if (slotIndex == -1) throw new System.ArgumentException(string.Format("Slot '{0}' does not exist in skeleton.", slotName), "slotName");
|
||||
skin.SetAttachment(slotIndex, keyName, attachment);
|
||||
}
|
||||
|
||||
/// <summary>Adds skin items from another skin. For items that already exist, the previous values are replaced.</summary>
|
||||
public static void AddAttachments (this Skin skin, Skin otherSkin) {
|
||||
if (otherSkin == null) return;
|
||||
otherSkin.CopyTo(skin, true, false);
|
||||
}
|
||||
|
||||
/// <summary>Gets an attachment from the skin for the specified slot index and name.</summary>
|
||||
public static Attachment GetAttachment (this Skin skin, string slotName, string keyName, Skeleton skeleton) {
|
||||
int slotIndex = skeleton.FindSlotIndex(slotName);
|
||||
if (skeleton == null) throw new System.ArgumentNullException("skeleton", "skeleton cannot be null.");
|
||||
if (slotIndex == -1) throw new System.ArgumentException(string.Format("Slot '{0}' does not exist in skeleton.", slotName), "slotName");
|
||||
return skin.GetAttachment(slotIndex, keyName);
|
||||
}
|
||||
|
||||
/// <summary>Adds an attachment to the skin for the specified slot index and name. If the name already exists for the slot, the previous value is replaced.</summary>
|
||||
public static void SetAttachment (this Skin skin, int slotIndex, string keyName, Attachment attachment) {
|
||||
skin.SetAttachment(slotIndex, keyName, attachment);
|
||||
}
|
||||
|
||||
public static void RemoveAttachment (this Skin skin, string slotName, string keyName, SkeletonData skeletonData) {
|
||||
int slotIndex = skeletonData.FindSlotIndex(slotName);
|
||||
if (skeletonData == null) throw new System.ArgumentNullException("skeletonData", "skeletonData cannot be null.");
|
||||
if (slotIndex == -1) throw new System.ArgumentException(string.Format("Slot '{0}' does not exist in skeleton.", slotName), "slotName");
|
||||
skin.RemoveAttachment(slotIndex, keyName);
|
||||
}
|
||||
|
||||
public static void Clear (this Skin skin) {
|
||||
skin.Attachments.Clear();
|
||||
}
|
||||
|
||||
//[System.Obsolete]
|
||||
public static void Append (this Skin destination, Skin source) {
|
||||
source.CopyTo(destination, true, false);
|
||||
}
|
||||
|
||||
public static void CopyTo (this Skin source, Skin destination, bool overwrite, bool cloneAttachments, bool cloneMeshesAsLinked = true) {
|
||||
var sourceAttachments = source.Attachments;
|
||||
var destinationAttachments = destination.Attachments;
|
||||
var destinationBones = destination.Bones;
|
||||
var destinationConstraints = destination.Constraints;
|
||||
|
||||
if (cloneAttachments) {
|
||||
if (overwrite) {
|
||||
foreach (var e in sourceAttachments) {
|
||||
Attachment clonedAttachment = e.Value.GetCopy(cloneMeshesAsLinked);
|
||||
destinationAttachments[new Skin.SkinEntry(e.Key.SlotIndex, e.Key.Name, clonedAttachment)] = clonedAttachment;
|
||||
}
|
||||
} else {
|
||||
foreach (var e in sourceAttachments) {
|
||||
if (destinationAttachments.ContainsKey(e.Key)) continue;
|
||||
Attachment clonedAttachment = e.Value.GetCopy(cloneMeshesAsLinked);
|
||||
destinationAttachments.Add(new Skin.SkinEntry(e.Key.SlotIndex, e.Key.Name, clonedAttachment), clonedAttachment);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (overwrite) {
|
||||
foreach (var e in sourceAttachments)
|
||||
destinationAttachments[e.Key] = e.Value;
|
||||
} else {
|
||||
foreach (var e in sourceAttachments) {
|
||||
if (destinationAttachments.ContainsKey(e.Key)) continue;
|
||||
destinationAttachments.Add(e.Key, e.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (BoneData data in source.bones)
|
||||
if (!destinationBones.Contains(data)) destinationBones.Add(data);
|
||||
|
||||
foreach (ConstraintData data in source.constraints)
|
||||
if (!destinationConstraints.Contains(data)) destinationConstraints.Add(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f4692b9527684d048862210ba3f9834e
|
||||
timeCreated: 1563321428
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,91 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated January 1, 2020. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2020, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software
|
||||
* or otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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
|
||||
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections;
|
||||
|
||||
namespace Spine.Unity.AnimationTools {
|
||||
public static class TimelineExtensions {
|
||||
|
||||
/// <summary>Evaluates the resulting value of a TranslateTimeline at a given time.
|
||||
/// SkeletonData can be accessed from Skeleton.Data or from SkeletonDataAsset.GetSkeletonData.
|
||||
/// If no SkeletonData is given, values are computed relative to setup pose instead of local-absolute.</summary>
|
||||
public static Vector2 Evaluate (this TranslateTimeline timeline, float time, SkeletonData skeletonData = null) {
|
||||
const int PREV_TIME = -3, PREV_X = -2, PREV_Y = -1;
|
||||
const int X = 1, Y = 2;
|
||||
|
||||
var frames = timeline.frames;
|
||||
if (time < frames[0]) return Vector2.zero;
|
||||
|
||||
float x, y;
|
||||
if (time >= frames[frames.Length - TranslateTimeline.ENTRIES]) { // Time is after last frame.
|
||||
x = frames[frames.Length + PREV_X];
|
||||
y = frames[frames.Length + PREV_Y];
|
||||
}
|
||||
else {
|
||||
// Interpolate between the previous frame and the current frame.
|
||||
int frame = Animation.BinarySearch(frames, time, TranslateTimeline.ENTRIES);
|
||||
x = frames[frame + PREV_X];
|
||||
y = frames[frame + PREV_Y];
|
||||
float frameTime = frames[frame];
|
||||
float percent = timeline.GetCurvePercent(frame / TranslateTimeline.ENTRIES - 1,
|
||||
1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime));
|
||||
|
||||
x += (frames[frame + X] - x) * percent;
|
||||
y += (frames[frame + Y] - y) * percent;
|
||||
}
|
||||
|
||||
Vector2 xy = new Vector2(x, y);
|
||||
if (skeletonData == null) {
|
||||
return xy;
|
||||
}
|
||||
else {
|
||||
var boneData = skeletonData.bones.Items[timeline.boneIndex];
|
||||
return xy + new Vector2(boneData.x, boneData.y);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Gets the translate timeline for a given boneIndex.
|
||||
/// You can get the boneIndex using SkeletonData.FindBoneIndex.
|
||||
/// The root bone is always boneIndex 0.
|
||||
/// This will return null if a TranslateTimeline is not found.</summary>
|
||||
public static TranslateTimeline FindTranslateTimelineForBone (this Animation a, int boneIndex) {
|
||||
foreach (var timeline in a.timelines) {
|
||||
if (timeline.GetType().IsSubclassOf(typeof(TranslateTimeline)))
|
||||
continue;
|
||||
|
||||
var translateTimeline = timeline as TranslateTimeline;
|
||||
if (translateTimeline != null && translateTimeline.boneIndex == boneIndex)
|
||||
return translateTimeline;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 07807fefbff25484ba41b1d16911fb0e
|
||||
timeCreated: 1591974498
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,9 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 15ac4befbee15d845ac289de3ab6d3d4
|
||||
folderAsset: yes
|
||||
timeCreated: 1455486167
|
||||
licenseType: Free
|
||||
DefaultImporter:
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated January 1, 2020. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2020, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software
|
||||
* or otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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
|
||||
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System;
|
||||
|
||||
namespace Spine.Unity {
|
||||
/// <summary>
|
||||
/// Use this as a condition-blocking yield instruction for Unity Coroutines.
|
||||
/// The routine will pause until the AnimationState.TrackEntry fires any of the
|
||||
/// configured events.
|
||||
/// <p/>
|
||||
/// See the <see cref="http://esotericsoftware.com/spine-unity-events">Spine Unity Events documentation page</see>
|
||||
/// and <see cref="http://esotericsoftware.com/spine-api-reference#AnimationStateListener"/>
|
||||
/// for more information on when track events will be triggered.</summary>
|
||||
public class WaitForSpineAnimation : IEnumerator {
|
||||
|
||||
[Flags]
|
||||
public enum AnimationEventTypes
|
||||
{
|
||||
Start = 1,
|
||||
Interrupt = 2,
|
||||
End = 4,
|
||||
Dispose = 8,
|
||||
Complete = 16
|
||||
}
|
||||
|
||||
bool m_WasFired = false;
|
||||
|
||||
public WaitForSpineAnimation (Spine.TrackEntry trackEntry, AnimationEventTypes eventsToWaitFor) {
|
||||
SafeSubscribe(trackEntry, eventsToWaitFor);
|
||||
}
|
||||
|
||||
#region Reuse
|
||||
/// <summary>
|
||||
/// One optimization high-frequency YieldInstruction returns is to cache instances to minimize GC pressure.
|
||||
/// Use NowWaitFor to reuse the same instance of WaitForSpineAnimationComplete.</summary>
|
||||
public WaitForSpineAnimation NowWaitFor (Spine.TrackEntry trackEntry, AnimationEventTypes eventsToWaitFor) {
|
||||
SafeSubscribe(trackEntry, eventsToWaitFor);
|
||||
return this;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region IEnumerator
|
||||
bool IEnumerator.MoveNext () {
|
||||
if (m_WasFired) {
|
||||
((IEnumerator)this).Reset(); // auto-reset for YieldInstruction reuse
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
void IEnumerator.Reset () { m_WasFired = false; }
|
||||
object IEnumerator.Current { get { return null; } }
|
||||
#endregion
|
||||
|
||||
protected void SafeSubscribe (Spine.TrackEntry trackEntry, AnimationEventTypes eventsToWaitFor) {
|
||||
if (trackEntry == null) {
|
||||
// Break immediately if trackEntry is null.
|
||||
Debug.LogWarning("TrackEntry was null. Coroutine will continue immediately.");
|
||||
m_WasFired = true;
|
||||
}
|
||||
else {
|
||||
if ((eventsToWaitFor & AnimationEventTypes.Start) != 0)
|
||||
trackEntry.Start += HandleComplete;
|
||||
if ((eventsToWaitFor & AnimationEventTypes.Interrupt) != 0)
|
||||
trackEntry.Interrupt += HandleComplete;
|
||||
if ((eventsToWaitFor & AnimationEventTypes.End) != 0)
|
||||
trackEntry.End += HandleComplete;
|
||||
if ((eventsToWaitFor & AnimationEventTypes.Dispose) != 0)
|
||||
trackEntry.Dispose += HandleComplete;
|
||||
if ((eventsToWaitFor & AnimationEventTypes.Complete) != 0)
|
||||
trackEntry.Complete += HandleComplete;
|
||||
}
|
||||
}
|
||||
|
||||
void HandleComplete (TrackEntry trackEntry) {
|
||||
m_WasFired = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d9be5adcaf0003849a1d181173c19635
|
||||
timeCreated: 1566289729
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated January 1, 2020. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2020, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software
|
||||
* or otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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
|
||||
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using Spine;
|
||||
|
||||
namespace Spine.Unity {
|
||||
/// <summary>
|
||||
/// Use this as a condition-blocking yield instruction for Unity Coroutines.
|
||||
/// The routine will pause until the AnimationState.TrackEntry fires its Complete event.
|
||||
/// It can be configured to trigger on the End event as well to cover interruption.
|
||||
/// <p/>
|
||||
/// See the <see cref="http://esotericsoftware.com/spine-unity-events">Spine Unity Events documentation page</see>
|
||||
/// and <see cref="http://esotericsoftware.com/spine-api-reference#AnimationStateListener"/>
|
||||
/// for more information on when track events will be triggered.</summary>
|
||||
public class WaitForSpineAnimationComplete : WaitForSpineAnimation, IEnumerator {
|
||||
|
||||
public WaitForSpineAnimationComplete (Spine.TrackEntry trackEntry, bool includeEndEvent = false) :
|
||||
base(trackEntry,
|
||||
includeEndEvent ? (AnimationEventTypes.Complete | AnimationEventTypes.End) : AnimationEventTypes.Complete)
|
||||
{
|
||||
}
|
||||
|
||||
#region Reuse
|
||||
/// <summary>
|
||||
/// One optimization high-frequency YieldInstruction returns is to cache instances to minimize GC pressure.
|
||||
/// Use NowWaitFor to reuse the same instance of WaitForSpineAnimationComplete.</summary>
|
||||
public WaitForSpineAnimationComplete NowWaitFor (Spine.TrackEntry trackEntry, bool includeEndEvent = false) {
|
||||
SafeSubscribe(trackEntry,
|
||||
includeEndEvent ? (AnimationEventTypes.Complete | AnimationEventTypes.End) : AnimationEventTypes.Complete);
|
||||
return this;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a807dd9fb79db3545b6c2859a2bbfc0b
|
||||
timeCreated: 1449704018
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated January 1, 2020. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2020, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software
|
||||
* or otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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
|
||||
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using Spine;
|
||||
|
||||
namespace Spine.Unity {
|
||||
/// <summary>
|
||||
/// Use this as a condition-blocking yield instruction for Unity Coroutines.
|
||||
/// The routine will pause until the AnimationState.TrackEntry fires its End event.
|
||||
/// <p/>
|
||||
/// See the <see cref="http://esotericsoftware.com/spine-unity-events">Spine Unity Events documentation page</see>
|
||||
/// and <see cref="http://esotericsoftware.com/spine-api-reference#AnimationStateListener"/>
|
||||
/// for more information on when track events will be triggered.</summary>
|
||||
public class WaitForSpineAnimationEnd : WaitForSpineAnimation, IEnumerator {
|
||||
|
||||
public WaitForSpineAnimationEnd (Spine.TrackEntry trackEntry) :
|
||||
base(trackEntry, AnimationEventTypes.End)
|
||||
{
|
||||
}
|
||||
|
||||
#region Reuse
|
||||
/// <summary>
|
||||
/// One optimization high-frequency YieldInstruction returns is to cache instances to minimize GC pressure.
|
||||
/// Use NowWaitFor to reuse the same instance of WaitForSpineAnimationComplete.</summary>
|
||||
public WaitForSpineAnimationEnd NowWaitFor (Spine.TrackEntry trackEntry) {
|
||||
SafeSubscribe(trackEntry, AnimationEventTypes.End);
|
||||
return this;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3c5a5fe930d1ab24da154d76b24c2747
|
||||
timeCreated: 1566288961
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated January 1, 2020. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2020, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software
|
||||
* or otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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
|
||||
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using Spine;
|
||||
|
||||
namespace Spine.Unity {
|
||||
/// <summary>
|
||||
/// Use this as a condition-blocking yield instruction for Unity Coroutines.
|
||||
/// The routine will pause until the AnimationState fires an event matching the given event name or EventData reference.</summary>
|
||||
public class WaitForSpineEvent : IEnumerator {
|
||||
|
||||
Spine.EventData m_TargetEvent;
|
||||
string m_EventName;
|
||||
Spine.AnimationState m_AnimationState;
|
||||
|
||||
bool m_WasFired = false;
|
||||
bool m_unsubscribeAfterFiring = false;
|
||||
|
||||
#region Constructors
|
||||
void Subscribe (Spine.AnimationState state, Spine.EventData eventDataReference, bool unsubscribe) {
|
||||
if (state == null) {
|
||||
Debug.LogWarning("AnimationState argument was null. Coroutine will continue immediately.");
|
||||
m_WasFired = true;
|
||||
return;
|
||||
} else if (eventDataReference == null) {
|
||||
Debug.LogWarning("eventDataReference argument was null. Coroutine will continue immediately.");
|
||||
m_WasFired = true;
|
||||
return;
|
||||
}
|
||||
|
||||
m_AnimationState = state;
|
||||
m_TargetEvent = eventDataReference;
|
||||
state.Event += HandleAnimationStateEvent;
|
||||
|
||||
m_unsubscribeAfterFiring = unsubscribe;
|
||||
|
||||
}
|
||||
|
||||
void SubscribeByName (Spine.AnimationState state, string eventName, bool unsubscribe) {
|
||||
if (state == null) {
|
||||
Debug.LogWarning("AnimationState argument was null. Coroutine will continue immediately.");
|
||||
m_WasFired = true;
|
||||
return;
|
||||
} else if (string.IsNullOrEmpty(eventName)) {
|
||||
Debug.LogWarning("eventName argument was null. Coroutine will continue immediately.");
|
||||
m_WasFired = true;
|
||||
return;
|
||||
}
|
||||
|
||||
m_AnimationState = state;
|
||||
m_EventName = eventName;
|
||||
state.Event += HandleAnimationStateEventByName;
|
||||
|
||||
m_unsubscribeAfterFiring = unsubscribe;
|
||||
}
|
||||
|
||||
public WaitForSpineEvent (Spine.AnimationState state, Spine.EventData eventDataReference, bool unsubscribeAfterFiring = true) {
|
||||
Subscribe(state, eventDataReference, unsubscribeAfterFiring);
|
||||
}
|
||||
|
||||
public WaitForSpineEvent (SkeletonAnimation skeletonAnimation, Spine.EventData eventDataReference, bool unsubscribeAfterFiring = true) {
|
||||
// If skeletonAnimation is invalid, its state will be null. Subscribe handles null states just fine.
|
||||
Subscribe(skeletonAnimation.state, eventDataReference, unsubscribeAfterFiring);
|
||||
}
|
||||
|
||||
public WaitForSpineEvent (Spine.AnimationState state, string eventName, bool unsubscribeAfterFiring = true) {
|
||||
SubscribeByName(state, eventName, unsubscribeAfterFiring);
|
||||
}
|
||||
|
||||
public WaitForSpineEvent (SkeletonAnimation skeletonAnimation, string eventName, bool unsubscribeAfterFiring = true) {
|
||||
// If skeletonAnimation is invalid, its state will be null. Subscribe handles null states just fine.
|
||||
SubscribeByName(skeletonAnimation.state, eventName, unsubscribeAfterFiring);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Event Handlers
|
||||
void HandleAnimationStateEventByName (Spine.TrackEntry trackEntry, Spine.Event e) {
|
||||
m_WasFired |= (e.Data.Name == m_EventName); // Check event name string match.
|
||||
if (m_WasFired && m_unsubscribeAfterFiring)
|
||||
m_AnimationState.Event -= HandleAnimationStateEventByName; // Unsubscribe after correct event fires.
|
||||
}
|
||||
|
||||
void HandleAnimationStateEvent (Spine.TrackEntry trackEntry, Spine.Event e) {
|
||||
m_WasFired |= (e.Data == m_TargetEvent); // Check event data reference match.
|
||||
if (m_WasFired && m_unsubscribeAfterFiring)
|
||||
m_AnimationState.Event -= HandleAnimationStateEvent; // Usubscribe after correct event fires.
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Reuse
|
||||
/// <summary>
|
||||
/// By default, WaitForSpineEvent will unsubscribe from the event immediately after it fires a correct matching event.
|
||||
/// If you want to reuse this WaitForSpineEvent instance on the same event, you can set this to false.</summary>
|
||||
public bool WillUnsubscribeAfterFiring { get { return m_unsubscribeAfterFiring; } set { m_unsubscribeAfterFiring = value; } }
|
||||
|
||||
public WaitForSpineEvent NowWaitFor (Spine.AnimationState state, Spine.EventData eventDataReference, bool unsubscribeAfterFiring = true) {
|
||||
((IEnumerator)this).Reset();
|
||||
Clear(state);
|
||||
Subscribe(state, eventDataReference, unsubscribeAfterFiring);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public WaitForSpineEvent NowWaitFor (Spine.AnimationState state, string eventName, bool unsubscribeAfterFiring = true) {
|
||||
((IEnumerator)this).Reset();
|
||||
Clear(state);
|
||||
SubscribeByName(state, eventName, unsubscribeAfterFiring);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
void Clear (Spine.AnimationState state) {
|
||||
state.Event -= HandleAnimationStateEvent;
|
||||
state.Event -= HandleAnimationStateEventByName;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region IEnumerator
|
||||
bool IEnumerator.MoveNext () {
|
||||
if (m_WasFired) {
|
||||
((IEnumerator)this).Reset(); // auto-reset for YieldInstruction reuse
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
void IEnumerator.Reset () { m_WasFired = false; }
|
||||
object IEnumerator.Current { get { return null; } }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fc166d883db083e469872998172f2d38
|
||||
timeCreated: 1449701857
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated January 1, 2020. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2020, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software
|
||||
* or otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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
|
||||
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using Spine;
|
||||
|
||||
namespace Spine.Unity {
|
||||
/// <summary>
|
||||
/// Use this as a condition-blocking yield instruction for Unity Coroutines.
|
||||
/// The routine will pause until the AnimationState.TrackEntry fires its End event.</summary>
|
||||
public class WaitForSpineTrackEntryEnd : IEnumerator {
|
||||
|
||||
bool m_WasFired = false;
|
||||
|
||||
public WaitForSpineTrackEntryEnd (Spine.TrackEntry trackEntry) {
|
||||
SafeSubscribe(trackEntry);
|
||||
}
|
||||
|
||||
void HandleEnd (TrackEntry trackEntry) {
|
||||
m_WasFired = true;
|
||||
}
|
||||
|
||||
void SafeSubscribe (Spine.TrackEntry trackEntry) {
|
||||
if (trackEntry == null) {
|
||||
// Break immediately if trackEntry is null.
|
||||
Debug.LogWarning("TrackEntry was null. Coroutine will continue immediately.");
|
||||
m_WasFired = true;
|
||||
} else {
|
||||
trackEntry.End += HandleEnd;
|
||||
}
|
||||
}
|
||||
|
||||
#region Reuse
|
||||
/// <summary>
|
||||
/// One optimization high-frequency YieldInstruction returns is to cache instances to minimize GC pressure.
|
||||
/// Use NowWaitFor to reuse the same instance of WaitForSpineAnimationEnd.</summary>
|
||||
public WaitForSpineTrackEntryEnd NowWaitFor (Spine.TrackEntry trackEntry) {
|
||||
SafeSubscribe(trackEntry);
|
||||
return this;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region IEnumerator
|
||||
bool IEnumerator.MoveNext () {
|
||||
if (m_WasFired) {
|
||||
((IEnumerator)this).Reset(); // auto-reset for YieldInstruction reuse
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
void IEnumerator.Reset () { m_WasFired = false; }
|
||||
object IEnumerator.Current { get { return null; } }
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8036c6c2897d2764db92f632d2aef568
|
||||
timeCreated: 1480672707
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Reference in New Issue
Block a user