This commit is contained in:
JA
2026-06-27 03:37:16 +08:00
parent 7a8d4a5d83
commit 3059e71422
465 changed files with 2675 additions and 58818 deletions

View File

@@ -1,262 +0,0 @@
/******************************************************************************
* 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;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using CompatibilityProblemInfo = Spine.Unity.SkeletonDataCompatibility.CompatibilityProblemInfo;
namespace Spine.Unity {
[CreateAssetMenu(fileName = "New SkeletonDataAsset", menuName = "Spine/SkeletonData Asset")]
public class SkeletonDataAsset : ScriptableObject {
#region Inspector
public AtlasAssetBase[] atlasAssets = new AtlasAssetBase[0];
#if SPINE_TK2D
public tk2dSpriteCollectionData spriteCollection;
public float scale = 1f;
#else
public float scale = 0.01f;
#endif
public TextAsset skeletonJSON;
public bool isUpgradingBlendModeMaterials = false;
public BlendModeMaterials blendModeMaterials = new BlendModeMaterials();
[Tooltip("Use SkeletonDataModifierAssets to apply changes to the SkeletonData after being loaded, such as apply blend mode Materials to Attachments under slots with special blend modes.")]
public List<SkeletonDataModifierAsset> skeletonDataModifiers = new List<SkeletonDataModifierAsset>();
[SpineAnimation(includeNone: false)]
public string[] fromAnimation = new string[0];
[SpineAnimation(includeNone: false)]
public string[] toAnimation = new string[0];
public float[] duration = new float[0];
public float defaultMix;
public RuntimeAnimatorController controller;
public bool IsLoaded { get { return this.skeletonData != null; } }
void Reset () {
Clear();
}
#endregion
SkeletonData skeletonData;
AnimationStateData stateData;
#region Runtime Instantiation
/// <summary>
/// Creates a runtime SkeletonDataAsset.</summary>
public static SkeletonDataAsset CreateRuntimeInstance (TextAsset skeletonDataFile, AtlasAssetBase atlasAsset, bool initialize, float scale = 0.01f) {
return CreateRuntimeInstance(skeletonDataFile, new [] {atlasAsset}, initialize, scale);
}
/// <summary>
/// Creates a runtime SkeletonDataAsset.</summary>
public static SkeletonDataAsset CreateRuntimeInstance (TextAsset skeletonDataFile, AtlasAssetBase[] atlasAssets, bool initialize, float scale = 0.01f) {
SkeletonDataAsset skeletonDataAsset = ScriptableObject.CreateInstance<SkeletonDataAsset>();
skeletonDataAsset.Clear();
skeletonDataAsset.skeletonJSON = skeletonDataFile;
skeletonDataAsset.atlasAssets = atlasAssets;
skeletonDataAsset.scale = scale;
if (initialize)
skeletonDataAsset.GetSkeletonData(true);
return skeletonDataAsset;
}
#endregion
/// <summary>Clears the loaded SkeletonData and AnimationStateData. Use this to force a reload for the next time GetSkeletonData is called.</summary>
public void Clear () {
skeletonData = null;
stateData = null;
}
public AnimationStateData GetAnimationStateData () {
if (stateData != null)
return stateData;
GetSkeletonData(false);
return stateData;
}
/// <summary>Loads, caches and returns the SkeletonData from the skeleton data file. Returns the cached SkeletonData after the first time it is called. Pass false to prevent direct errors from being logged.</summary>
public SkeletonData GetSkeletonData (bool quiet) {
if (skeletonJSON == null) {
if (!quiet)
Debug.LogError("Skeleton JSON file not set for SkeletonData asset: " + name, this);
Clear();
return null;
}
// Disabled to support attachmentless/skinless SkeletonData.
// if (atlasAssets == null) {
// atlasAssets = new AtlasAsset[0];
// if (!quiet)
// Debug.LogError("Atlas not set for SkeletonData asset: " + name, this);
// Clear();
// return null;
// }
// #if !SPINE_TK2D
// if (atlasAssets.Length == 0) {
// Clear();
// return null;
// }
// #else
// if (atlasAssets.Length == 0 && spriteCollection == null) {
// Clear();
// return null;
// }
// #endif
if (skeletonData != null)
return skeletonData;
AttachmentLoader attachmentLoader;
float skeletonDataScale;
Atlas[] atlasArray = this.GetAtlasArray();
#if !SPINE_TK2D
attachmentLoader = (atlasArray.Length == 0) ? (AttachmentLoader)new RegionlessAttachmentLoader() : (AttachmentLoader)new AtlasAttachmentLoader(atlasArray);
skeletonDataScale = scale;
#else
if (spriteCollection != null) {
attachmentLoader = new Spine.Unity.TK2D.SpriteCollectionAttachmentLoader(spriteCollection);
skeletonDataScale = (1.0f / (spriteCollection.invOrthoSize * spriteCollection.halfTargetHeight) * scale);
} else {
if (atlasArray.Length == 0) {
Reset();
if (!quiet) Debug.LogError("Atlas not set for SkeletonData asset: " + name, this);
return null;
}
attachmentLoader = new AtlasAttachmentLoader(atlasArray);
skeletonDataScale = scale;
}
#endif
bool hasBinaryExtension = skeletonJSON.name.ToLower().Contains(".skel");
SkeletonData loadedSkeletonData = null;
try {
if (hasBinaryExtension)
loadedSkeletonData = SkeletonDataAsset.ReadSkeletonData(skeletonJSON.bytes, attachmentLoader, skeletonDataScale);
else
loadedSkeletonData = SkeletonDataAsset.ReadSkeletonData(skeletonJSON.text, attachmentLoader, skeletonDataScale);
} catch (Exception ex) {
if (!quiet)
Debug.LogError("Error reading skeleton JSON file for SkeletonData asset: " + name + "\n" + ex.Message + "\n" + ex.StackTrace, skeletonJSON);
}
#if UNITY_EDITOR
if (loadedSkeletonData == null && !quiet && skeletonJSON != null) {
string problemDescription = null;
bool isSpineSkeletonData;
SkeletonDataCompatibility.VersionInfo fileVersion = SkeletonDataCompatibility.GetVersionInfo(skeletonJSON, out isSpineSkeletonData, ref problemDescription);
if (problemDescription != null) {
if (!quiet)
Debug.LogError(problemDescription, skeletonJSON);
return null;
}
CompatibilityProblemInfo compatibilityProblemInfo = SkeletonDataCompatibility.GetCompatibilityProblemInfo(fileVersion);
if (compatibilityProblemInfo != null) {
SkeletonDataCompatibility.DisplayCompatibilityProblem(compatibilityProblemInfo.DescriptionString(), skeletonJSON);
return null;
}
}
#endif
if (loadedSkeletonData == null)
return null;
if (skeletonDataModifiers != null) {
foreach (var modifier in skeletonDataModifiers) {
if (modifier != null && !(isUpgradingBlendModeMaterials && modifier is BlendModeMaterialsAsset)) {
modifier.Apply(loadedSkeletonData);
}
}
}
if (!isUpgradingBlendModeMaterials)
blendModeMaterials.ApplyMaterials(loadedSkeletonData);
this.InitializeWithData(loadedSkeletonData);
return skeletonData;
}
internal void InitializeWithData (SkeletonData sd) {
this.skeletonData = sd;
this.stateData = new AnimationStateData(skeletonData);
FillStateData();
}
public void FillStateData () {
if (stateData != null) {
stateData.defaultMix = defaultMix;
for (int i = 0, n = fromAnimation.Length; i < n; i++) {
if (fromAnimation[i].Length == 0 || toAnimation[i].Length == 0)
continue;
stateData.SetMix(fromAnimation[i], toAnimation[i], duration[i]);
}
}
}
internal Atlas[] GetAtlasArray () {
var returnList = new System.Collections.Generic.List<Atlas>(atlasAssets.Length);
for (int i = 0; i < atlasAssets.Length; i++) {
var aa = atlasAssets[i];
if (aa == null) continue;
var a = aa.GetAtlas();
if (a == null) continue;
returnList.Add(a);
}
return returnList.ToArray();
}
internal static SkeletonData ReadSkeletonData (byte[] bytes, AttachmentLoader attachmentLoader, float scale) {
using (var input = new MemoryStream(bytes)) {
var binary = new SkeletonBinary(attachmentLoader) {
Scale = scale
};
return binary.ReadSkeletonData(input);
}
}
internal static SkeletonData ReadSkeletonData (string text, AttachmentLoader attachmentLoader, float scale) {
var input = new StringReader(text);
var json = new SkeletonJson(attachmentLoader) {
Scale = scale
};
return json.ReadSkeletonData(input);
}
}
}

View File

@@ -1,20 +0,0 @@
fileFormatVersion: 2
guid: f1b3b4b945939a54ea0b23d3396115fb
timeCreated: 1536403985
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences:
- multiplyMaterialTemplate: {fileID: 2100000, guid: 53bf0ab317d032d418cf1252d68f51df,
type: 2}
- screenMaterialTemplate: {fileID: 2100000, guid: 73f0f46d3177c614baf0fa48d646a9be,
type: 2}
- additiveMaterialTemplate: {fileID: 2100000, guid: 4deba332d47209e4780b3c5fcf0e3745,
type: 2}
- skeletonJSON: {instanceID: 0}
- controller: {instanceID: 0}
executionOrder: 0
icon: {fileID: 2800000, guid: 68defdbc95b30a74a9ad396bfc9a2277, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,215 +0,0 @@
/******************************************************************************
* 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 System.IO;
using UnityEngine;
using System;
#if UNITY_EDITOR
using System.Globalization;
using System.Text.RegularExpressions;
#endif
namespace Spine.Unity {
public static class SkeletonDataCompatibility {
#if UNITY_EDITOR
static readonly int[][] compatibleBinaryVersions = { new[] { 3, 8, 0 } };
static readonly int[][] compatibleJsonVersions = { new[] { 3, 8, 0 } };
static bool wasVersionDialogShown = false;
static readonly Regex jsonVersionRegex = new Regex(@"""spine""\s*:\s*""([^""]+)""", RegexOptions.CultureInvariant);
#endif
public enum SourceType {
Json,
Binary
}
[System.Serializable]
public class VersionInfo {
public string rawVersion = null;
public int[] version = null;
public SourceType sourceType;
}
[System.Serializable]
public class CompatibilityProblemInfo {
public VersionInfo actualVersion;
public int[][] compatibleVersions;
public string explicitProblemDescription = null;
public string DescriptionString () {
if (!string.IsNullOrEmpty(explicitProblemDescription))
return explicitProblemDescription;
string compatibleVersionString = "";
string optionalOr = null;
foreach (int[] version in compatibleVersions) {
compatibleVersionString += string.Format("{0}{1}.{2}", optionalOr, version[0], version[1]);
optionalOr = " or ";
}
return string.Format("Skeleton data could not be loaded. Data version: {0}. Required version: {1}.\nPlease re-export skeleton data with Spine {1} or change runtime to version {2}.{3}.",
actualVersion.rawVersion, compatibleVersionString, actualVersion.version[0], actualVersion.version[1]);
}
}
#if UNITY_EDITOR
public static VersionInfo GetVersionInfo (TextAsset asset, out bool isSpineSkeletonData, ref string problemDescription) {
isSpineSkeletonData = false;
if (asset == null)
return null;
VersionInfo fileVersion = new VersionInfo();
bool hasBinaryExtension = asset.name.Contains(".skel");
fileVersion.sourceType = hasBinaryExtension ? SourceType.Binary : SourceType.Json;
bool isJsonFileByContent = IsJsonFile(asset);
if (hasBinaryExtension == isJsonFileByContent) {
if (hasBinaryExtension) {
problemDescription = string.Format("Failed to read '{0}'. Extension is '.skel.bytes' but content looks like a '.json' file.\n"
+ "Did you choose the wrong extension upon export?\n", asset.name);
}
else {
problemDescription = string.Format("Failed to read '{0}'. Extension is '.json' but content looks like binary 'skel.bytes' file.\n"
+ "Did you choose the wrong extension upon export?\n", asset.name);
}
isSpineSkeletonData = false;
return null;
}
if (fileVersion.sourceType == SourceType.Binary) {
try {
using (var memStream = new MemoryStream(asset.bytes)) {
fileVersion.rawVersion = SkeletonBinary.GetVersionString(memStream);
}
}
catch (System.Exception e) {
problemDescription = string.Format("Failed to read '{0}'. It is likely not a binary Spine SkeletonData file.\n{1}", asset.name, e);
isSpineSkeletonData = false;
return null;
}
}
else {
Match match = jsonVersionRegex.Match(asset.text);
if (match != null) {
fileVersion.rawVersion = match.Groups[1].Value;
}
else {
object obj = Json.Deserialize(new StringReader(asset.text));
if (obj == null) {
problemDescription = string.Format("'{0}' is not valid JSON.", asset.name);
isSpineSkeletonData = false;
return null;
}
var root = obj as Dictionary<string, object>;
if (root == null) {
problemDescription = string.Format("'{0}' is not compatible JSON. Parser returned an incorrect type while parsing version info.", asset.name);
isSpineSkeletonData = false;
return null;
}
if (root.ContainsKey("skeleton")) {
var skeletonInfo = (Dictionary<string, object>)root["skeleton"];
object jv;
skeletonInfo.TryGetValue("spine", out jv);
fileVersion.rawVersion = jv as string;
}
}
}
if (string.IsNullOrEmpty(fileVersion.rawVersion)) {
// very likely not a Spine skeleton json file at all. Could be another valid json file, don't report errors.
isSpineSkeletonData = false;
return null;
}
var versionSplit = fileVersion.rawVersion.Split('.');
try {
fileVersion.version = new[]{ int.Parse(versionSplit[0], CultureInfo.InvariantCulture),
int.Parse(versionSplit[1], CultureInfo.InvariantCulture) };
}
catch (System.Exception e) {
problemDescription = string.Format("Failed to read version info at skeleton '{0}'. It is likely not a valid Spine SkeletonData file.\n{1}", asset.name, e);
isSpineSkeletonData = false;
return null;
}
isSpineSkeletonData = true;
return fileVersion;
}
public static bool IsJsonFile (TextAsset file) {
byte[] content = file.bytes;
const int maxCharsToCheck = 256;
int numCharsToCheck = Math.Min(content.Length, maxCharsToCheck);
int i = 0;
if (content.Length >= 3 && content[0] == 0xEF && content[1] == 0xBB && content[2] == 0xBF) // skip potential BOM
i = 3;
for (; i < numCharsToCheck; ++i) {
char c = (char)content[i];
if (char.IsWhiteSpace(c))
continue;
return c == '{';
}
return true;
}
public static CompatibilityProblemInfo GetCompatibilityProblemInfo (VersionInfo fileVersion) {
if (fileVersion == null) {
return null; // it's most likely not a Spine skeleton file, e.g. another json file. don't report problems.
}
CompatibilityProblemInfo info = new CompatibilityProblemInfo();
info.actualVersion = fileVersion;
info.compatibleVersions = (fileVersion.sourceType == SourceType.Binary) ? compatibleBinaryVersions
: compatibleJsonVersions;
foreach (var compatibleVersion in info.compatibleVersions) {
bool majorMatch = fileVersion.version[0] == compatibleVersion[0];
bool minorMatch = fileVersion.version[1] == compatibleVersion[1];
if (majorMatch && minorMatch) {
return null; // is compatible, thus no problem info returned
}
}
return info;
}
public static void DisplayCompatibilityProblem (string descriptionString, TextAsset spineJson) {
if (!wasVersionDialogShown) {
wasVersionDialogShown = true;
UnityEditor.EditorUtility.DisplayDialog("Version mismatch!", descriptionString, "OK");
}
Debug.LogError(string.Format("Error importing skeleton '{0}': {1}",
spineJson.name, descriptionString), spineJson);
}
#endif // UNITY_EDITOR
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 4224df6e20549f0449154531ae080201
timeCreated: 1567002861
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,39 +0,0 @@
/******************************************************************************
* 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;
using System.Collections.Generic;
using UnityEngine;
namespace Spine.Unity {
/// <summary>Can be stored by SkeletonDataAsset to automatically apply modifications to loaded SkeletonData.</summary>
public abstract class SkeletonDataModifierAsset : ScriptableObject {
public abstract void Apply (SkeletonData skeletonData);
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 79a44aba1f342f440965874280b4c318
timeCreated: 1536412736
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,121 +0,0 @@
/******************************************************************************
* 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 Spine.Unity.AnimationTools;
namespace Spine.Unity {
/// <summary>
/// Add this component to a SkeletonMecanim GameObject
/// to turn motion of a selected root bone into Transform or RigidBody motion.
/// Local bone translation movement is used as motion.
/// All top-level bones of the skeleton are moved to compensate the root
/// motion bone location, keeping the distance relationship between bones intact.
/// </summary>
/// <remarks>
/// Only compatible with <c>SkeletonMecanim</c>.
/// For <c>SkeletonAnimation</c> or <c>SkeletonGraphic</c> please use
/// <see cref="SkeletonRootMotion">SkeletonRootMotion</see> instead.
/// </remarks>
[HelpURL("http://esotericsoftware.com/spine-unity#SkeletonMecanimRootMotion")]
public class SkeletonMecanimRootMotion : SkeletonRootMotionBase {
#region Inspector
const int DefaultMecanimLayerFlags = -1;
public int mecanimLayerFlags = DefaultMecanimLayerFlags;
#endregion
protected Vector2 movementDelta;
SkeletonMecanim skeletonMecanim;
public SkeletonMecanim SkeletonMecanim {
get {
return skeletonMecanim ? skeletonMecanim : skeletonMecanim = GetComponent<SkeletonMecanim>();
}
}
public override Vector2 GetRemainingRootMotion (int layerIndex) {
var pair = skeletonMecanim.Translator.GetActiveAnimationAndTime(layerIndex);
var animation = pair.Key;
var time = pair.Value;
if (animation == null)
return Vector2.zero;
float start = time;
float end = animation.duration;
return GetAnimationRootMotion(start, end, animation);
}
public override RootMotionInfo GetRootMotionInfo (int layerIndex) {
var pair = skeletonMecanim.Translator.GetActiveAnimationAndTime(layerIndex);
var animation = pair.Key;
var time = pair.Value;
if (animation == null)
return new RootMotionInfo();
return GetAnimationRootMotionInfo(animation, time);
}
protected override void Reset () {
base.Reset();
mecanimLayerFlags = DefaultMecanimLayerFlags;
}
protected override void Start () {
base.Start();
skeletonMecanim = GetComponent<SkeletonMecanim>();
if (skeletonMecanim) {
skeletonMecanim.Translator.OnClipApplied -= OnClipApplied;
skeletonMecanim.Translator.OnClipApplied += OnClipApplied;
}
}
void OnClipApplied(Spine.Animation animation, int layerIndex, float weight,
float time, float lastTime, bool playsBackward) {
if (((mecanimLayerFlags & 1<<layerIndex) == 0) || weight == 0)
return;
if (!playsBackward) {
movementDelta += weight * GetAnimationRootMotion(lastTime, time, animation);
}
else {
movementDelta -= weight * GetAnimationRootMotion(time, lastTime, animation);
}
}
protected override Vector2 CalculateAnimationsMovementDelta () {
// Note: movement delta is not gather after animation but
// in OnClipApplied after every applied animation.
Vector2 result = movementDelta;
movementDelta = Vector2.zero;
return result;
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 95813afe390494344a6ce2cbc8bfb7d1
timeCreated: 1592849332
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,157 +0,0 @@
/******************************************************************************
* 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 Spine.Unity.AnimationTools;
namespace Spine.Unity {
/// <summary>
/// Add this component to a SkeletonAnimation or SkeletonGraphic GameObject
/// to turn motion of a selected root bone into Transform or RigidBody motion.
/// Local bone translation movement is used as motion.
/// All top-level bones of the skeleton are moved to compensate the root
/// motion bone location, keeping the distance relationship between bones intact.
/// </summary>
/// <remarks>
/// Only compatible with SkeletonAnimation (or other components that implement
/// ISkeletonComponent, ISkeletonAnimation and IAnimationStateComponent).
/// For <c>SkeletonMecanim</c> please use
/// <see cref="SkeletonMecanimRootMotion">SkeletonMecanimRootMotion</see> instead.
/// </remarks>
[HelpURL("http://esotericsoftware.com/spine-unity#SkeletonRootMotion")]
public class SkeletonRootMotion : SkeletonRootMotionBase {
#region Inspector
const int DefaultAnimationTrackFlags = -1;
public int animationTrackFlags = DefaultAnimationTrackFlags;
#endregion
AnimationState animationState;
Canvas canvas;
public override Vector2 GetRemainingRootMotion (int trackIndex) {
TrackEntry track = animationState.GetCurrent(trackIndex);
if (track == null)
return Vector2.zero;
var animation = track.Animation;
float start = track.AnimationTime;
float end = animation.duration;
return GetAnimationRootMotion(start, end, animation);
}
public override RootMotionInfo GetRootMotionInfo (int trackIndex) {
TrackEntry track = animationState.GetCurrent(trackIndex);
if (track == null)
return new RootMotionInfo();
var animation = track.Animation;
float time = track.AnimationTime;
return GetAnimationRootMotionInfo(track.Animation, time);
}
protected override float AdditionalScale {
get {
return canvas ? canvas.referencePixelsPerUnit: 1.0f;
}
}
protected override void Reset () {
base.Reset();
animationTrackFlags = DefaultAnimationTrackFlags;
}
protected override void Start () {
base.Start();
var animstateComponent = skeletonComponent as IAnimationStateComponent;
this.animationState = (animstateComponent != null) ? animstateComponent.AnimationState : null;
if (this.GetComponent<CanvasRenderer>() != null) {
canvas = this.GetComponentInParent<Canvas>();
}
}
protected override Vector2 CalculateAnimationsMovementDelta () {
Vector2 localDelta = Vector2.zero;
int trackCount = animationState.Tracks.Count;
for (int trackIndex = 0; trackIndex < trackCount; ++trackIndex) {
// note: animationTrackFlags != -1 below covers trackIndex >= 32,
// with -1 corresponding to entry "everything" of the dropdown list.
if (animationTrackFlags != -1 && (animationTrackFlags & 1 << trackIndex) == 0)
continue;
TrackEntry track = animationState.GetCurrent(trackIndex);
TrackEntry next = null;
while (track != null) {
var animation = track.Animation;
float start = track.animationLast;
float end = track.AnimationTime;
var currentDelta = GetAnimationRootMotion(start, end, animation);
if (currentDelta != Vector2.zero) {
ApplyMixAlphaToDelta(ref currentDelta, next, track);
localDelta += currentDelta;
}
// Traverse mixingFrom chain.
next = track;
track = track.mixingFrom;
}
}
return localDelta;
}
void ApplyMixAlphaToDelta (ref Vector2 currentDelta, TrackEntry next, TrackEntry track) {
// Apply mix alpha to the delta position (based on AnimationState.cs).
float mix;
if (next != null) {
if (next.mixDuration == 0) { // Single frame mix to undo mixingFrom changes.
mix = 1;
}
else {
mix = next.mixTime / next.mixDuration;
if (mix > 1) mix = 1;
}
float mixAndAlpha = track.alpha * next.interruptAlpha * (1 - mix);
currentDelta *= mixAndAlpha;
}
else {
if (track.mixDuration == 0) {
mix = 1;
}
else {
mix = track.alpha * (track.mixTime / track.mixDuration);
if (mix > 1) mix = 1;
}
currentDelta *= mix;
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: f21c9538588898a45a3da22bf4779ab3
timeCreated: 1591121072
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,322 +0,0 @@
/******************************************************************************
* 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 Spine.Unity.AnimationTools;
using System;
namespace Spine.Unity {
/// <summary>
/// Base class for skeleton root motion components.
/// </summary>
abstract public class SkeletonRootMotionBase : MonoBehaviour {
#region Inspector
[SpineBone]
[SerializeField]
protected string rootMotionBoneName = "root";
public bool transformPositionX = true;
public bool transformPositionY = true;
public float rootMotionScaleX = 1;
public float rootMotionScaleY = 1;
/// <summary>Skeleton space X translation per skeleton space Y translation root motion.</summary>
public float rootMotionTranslateXPerY = 0;
/// <summary>Skeleton space Y translation per skeleton space X translation root motion.</summary>
public float rootMotionTranslateYPerX = 0;
[Header("Optional")]
public Rigidbody2D rigidBody2D;
public Rigidbody rigidBody;
public bool UsesRigidbody {
get { return rigidBody != null || rigidBody2D != null; }
}
#endregion
protected ISkeletonComponent skeletonComponent;
protected Bone rootMotionBone;
protected int rootMotionBoneIndex;
protected List<Bone> topLevelBones = new List<Bone>();
protected Vector2 initialOffset = Vector2.zero;
protected Vector2 tempSkeletonDisplacement;
protected Vector2 rigidbodyDisplacement;
protected virtual void Reset () {
FindRigidbodyComponent();
}
protected virtual void Start () {
skeletonComponent = GetComponent<ISkeletonComponent>();
GatherTopLevelBones();
SetRootMotionBone(rootMotionBoneName);
if (rootMotionBone != null)
initialOffset = new Vector2(rootMotionBone.x, rootMotionBone.y);
var skeletonAnimation = skeletonComponent as ISkeletonAnimation;
if (skeletonAnimation != null) {
skeletonAnimation.UpdateLocal -= HandleUpdateLocal;
skeletonAnimation.UpdateLocal += HandleUpdateLocal;
}
}
protected virtual void FixedUpdate () {
if (!this.isActiveAndEnabled)
return; // Root motion is only applied when component is enabled.
if (rigidBody2D != null) {
rigidBody2D.MovePosition(new Vector2(transform.position.x, transform.position.y)
+ rigidbodyDisplacement);
}
if (rigidBody != null) {
rigidBody.MovePosition(transform.position
+ new Vector3(rigidbodyDisplacement.x, rigidbodyDisplacement.y, 0));
}
Vector2 parentBoneScale;
GetScaleAffectingRootMotion(out parentBoneScale);
ClearEffectiveBoneOffsets(parentBoneScale);
rigidbodyDisplacement = Vector2.zero;
tempSkeletonDisplacement = Vector2.zero;
}
protected virtual void OnDisable () {
rigidbodyDisplacement = Vector2.zero;
tempSkeletonDisplacement = Vector2.zero;
}
protected void FindRigidbodyComponent () {
rigidBody2D = this.GetComponent<Rigidbody2D>();
if (!rigidBody2D)
rigidBody = this.GetComponent<Rigidbody>();
if (!rigidBody2D && !rigidBody) {
rigidBody2D = this.GetComponentInParent<Rigidbody2D>();
if (!rigidBody2D)
rigidBody = this.GetComponentInParent<Rigidbody>();
}
}
protected virtual float AdditionalScale { get { return 1.0f; } }
abstract protected Vector2 CalculateAnimationsMovementDelta ();
abstract public Vector2 GetRemainingRootMotion (int trackIndex = 0);
public struct RootMotionInfo {
public Vector2 start;
public Vector2 current;
public Vector2 mid;
public Vector2 end;
public bool timeIsPastMid;
};
abstract public RootMotionInfo GetRootMotionInfo (int trackIndex = 0);
public void SetRootMotionBone (string name) {
var skeleton = skeletonComponent.Skeleton;
int index = skeleton.FindBoneIndex(name);
if (index >= 0) {
this.rootMotionBoneIndex = index;
this.rootMotionBone = skeleton.bones.Items[index];
}
else {
Debug.Log("Bone named \"" + name + "\" could not be found.");
this.rootMotionBoneIndex = 0;
this.rootMotionBone = skeleton.RootBone;
}
}
public void AdjustRootMotionToDistance (Vector2 distanceToTarget, int trackIndex = 0, bool adjustX = true, bool adjustY = true,
float minX = 0, float maxX = float.MaxValue, float minY = 0, float maxY = float.MaxValue,
bool allowXTranslation = false, bool allowYTranslation = false) {
Vector2 distanceToTargetSkeletonSpace = (Vector2)transform.InverseTransformVector(distanceToTarget);
Vector2 scaleAffectingRootMotion = GetScaleAffectingRootMotion();
if (UsesRigidbody)
distanceToTargetSkeletonSpace -= tempSkeletonDisplacement;
Vector2 remainingRootMotionSkeletonSpace = GetRemainingRootMotion(trackIndex);
remainingRootMotionSkeletonSpace.Scale(scaleAffectingRootMotion);
if (remainingRootMotionSkeletonSpace.x == 0)
remainingRootMotionSkeletonSpace.x = 0.0001f;
if (remainingRootMotionSkeletonSpace.y == 0)
remainingRootMotionSkeletonSpace.y = 0.0001f;
if (adjustX)
rootMotionScaleX = Math.Min(maxX, Math.Max(minX, distanceToTargetSkeletonSpace.x / remainingRootMotionSkeletonSpace.x));
if (adjustY)
rootMotionScaleY = Math.Min(maxY, Math.Max(minY, distanceToTargetSkeletonSpace.y / remainingRootMotionSkeletonSpace.y));
if (allowXTranslation)
rootMotionTranslateXPerY = (distanceToTargetSkeletonSpace.x - remainingRootMotionSkeletonSpace.x * rootMotionScaleX) / remainingRootMotionSkeletonSpace.y;
if (allowYTranslation)
rootMotionTranslateYPerX = (distanceToTargetSkeletonSpace.y - remainingRootMotionSkeletonSpace.y * rootMotionScaleY) / remainingRootMotionSkeletonSpace.x;
}
public Vector2 GetAnimationRootMotion (Animation animation) {
return GetAnimationRootMotion(0, animation.duration, animation);
}
public Vector2 GetAnimationRootMotion (float startTime, float endTime,
Animation animation) {
var timeline = animation.FindTranslateTimelineForBone(rootMotionBoneIndex);
if (timeline != null) {
return GetTimelineMovementDelta(startTime, endTime, timeline, animation);
}
return Vector2.zero;
}
public RootMotionInfo GetAnimationRootMotionInfo (Animation animation, float currentTime) {
RootMotionInfo rootMotion = new RootMotionInfo();
var timeline = animation.FindTranslateTimelineForBone(rootMotionBoneIndex);
if (timeline != null) {
float duration = animation.duration;
float mid = duration * 0.5f;
rootMotion.start = timeline.Evaluate(0);
rootMotion.current = timeline.Evaluate(currentTime);
rootMotion.mid = timeline.Evaluate(mid);
rootMotion.end = timeline.Evaluate(duration);
rootMotion.timeIsPastMid = currentTime > mid;
}
return rootMotion;
}
Vector2 GetTimelineMovementDelta (float startTime, float endTime,
TranslateTimeline timeline, Animation animation) {
Vector2 currentDelta;
if (startTime > endTime) // Looped
currentDelta = (timeline.Evaluate(animation.duration) - timeline.Evaluate(startTime))
+ (timeline.Evaluate(endTime) - timeline.Evaluate(0));
else if (startTime != endTime) // Non-looped
currentDelta = timeline.Evaluate(endTime) - timeline.Evaluate(startTime);
else
currentDelta = Vector2.zero;
return currentDelta;
}
void GatherTopLevelBones () {
topLevelBones.Clear();
var skeleton = skeletonComponent.Skeleton;
foreach (var bone in skeleton.Bones) {
if (bone.Parent == null)
topLevelBones.Add(bone);
}
}
void HandleUpdateLocal (ISkeletonAnimation animatedSkeletonComponent) {
if (!this.isActiveAndEnabled)
return; // Root motion is only applied when component is enabled.
var boneLocalDelta = CalculateAnimationsMovementDelta();
Vector2 parentBoneScale;
Vector2 skeletonDelta = GetSkeletonSpaceMovementDelta(boneLocalDelta, out parentBoneScale);
ApplyRootMotion(skeletonDelta, parentBoneScale);
}
void ApplyRootMotion (Vector2 skeletonDelta, Vector2 parentBoneScale) {
// Apply root motion to Transform or RigidBody;
if (UsesRigidbody) {
rigidbodyDisplacement += (Vector2)transform.TransformVector(skeletonDelta);
// Accumulated displacement is applied on the next Physics update in FixedUpdate.
// Until the next Physics update, tempBoneDisplacement is offsetting bone locations
// to prevent stutter which would otherwise occur if we don't move every Update.
tempSkeletonDisplacement += skeletonDelta;
SetEffectiveBoneOffsetsTo(tempSkeletonDisplacement, parentBoneScale);
}
else {
transform.position += transform.TransformVector(skeletonDelta);
ClearEffectiveBoneOffsets(parentBoneScale);
}
}
Vector2 GetScaleAffectingRootMotion () {
Vector2 parentBoneScale;
return GetScaleAffectingRootMotion(out parentBoneScale);
}
Vector2 GetScaleAffectingRootMotion (out Vector2 parentBoneScale) {
var skeleton = skeletonComponent.Skeleton;
Vector2 totalScale = Vector2.one;
totalScale.x *= skeleton.ScaleX;
totalScale.y *= skeleton.ScaleY;
parentBoneScale = Vector2.one;
Bone scaleBone = rootMotionBone;
while ((scaleBone = scaleBone.parent) != null) {
parentBoneScale.x *= scaleBone.ScaleX;
parentBoneScale.y *= scaleBone.ScaleY;
}
totalScale = Vector2.Scale(totalScale, parentBoneScale);
totalScale *= AdditionalScale;
return totalScale;
}
Vector2 GetSkeletonSpaceMovementDelta (Vector2 boneLocalDelta, out Vector2 parentBoneScale) {
Vector2 skeletonDelta = boneLocalDelta;
Vector2 totalScale = GetScaleAffectingRootMotion(out parentBoneScale);
skeletonDelta.Scale(totalScale);
Vector2 rootMotionTranslation = new Vector2(
rootMotionTranslateXPerY * skeletonDelta.y,
rootMotionTranslateYPerX * skeletonDelta.x);
skeletonDelta.x *= rootMotionScaleX;
skeletonDelta.y *= rootMotionScaleY;
skeletonDelta.x += rootMotionTranslation.x;
skeletonDelta.y += rootMotionTranslation.y;
if (!transformPositionX) skeletonDelta.x = 0f;
if (!transformPositionY) skeletonDelta.y = 0f;
return skeletonDelta;
}
void SetEffectiveBoneOffsetsTo (Vector2 displacementSkeletonSpace, Vector2 parentBoneScale) {
// Move top level bones in opposite direction of the root motion bone
var skeleton = skeletonComponent.Skeleton;
foreach (var topLevelBone in topLevelBones) {
if (topLevelBone == rootMotionBone) {
if (transformPositionX) topLevelBone.x = displacementSkeletonSpace.x / skeleton.ScaleX;
if (transformPositionY) topLevelBone.y = displacementSkeletonSpace.y / skeleton.ScaleY;
}
else {
float offsetX = (initialOffset.x - rootMotionBone.x) * parentBoneScale.x;
float offsetY = (initialOffset.y - rootMotionBone.y) * parentBoneScale.y;
if (transformPositionX) topLevelBone.x = (displacementSkeletonSpace.x / skeleton.ScaleX) + offsetX;
if (transformPositionY) topLevelBone.y = (displacementSkeletonSpace.y / skeleton.ScaleY) + offsetY;
}
}
}
void ClearEffectiveBoneOffsets (Vector2 parentBoneScale) {
SetEffectiveBoneOffsetsTo(Vector2.zero, parentBoneScale);
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: fc23a4f220b20024ab0592719f92587d
timeCreated: 1592849332
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,251 +0,0 @@
/******************************************************************************
* 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_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
#define NEW_PREFAB_SYSTEM
#endif
using UnityEngine;
namespace Spine.Unity {
#if NEW_PREFAB_SYSTEM
[ExecuteAlways]
#else
[ExecuteInEditMode]
#endif
[AddComponentMenu("Spine/SkeletonAnimation")]
[HelpURL("http://esotericsoftware.com/spine-unity#SkeletonAnimation-Component")]
public class SkeletonAnimation : SkeletonRenderer, ISkeletonAnimation, IAnimationStateComponent {
#region IAnimationStateComponent
/// <summary>
/// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it.
/// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start</summary>
public Spine.AnimationState state;
/// <summary>
/// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it.
/// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start</summary>
public Spine.AnimationState AnimationState {
get {
Initialize(false);
return this.state;
}
}
private bool wasUpdatedAfterInit = true;
#endregion
#region Bone Callbacks ISkeletonAnimation
protected event UpdateBonesDelegate _BeforeApply;
protected event UpdateBonesDelegate _UpdateLocal;
protected event UpdateBonesDelegate _UpdateWorld;
protected event UpdateBonesDelegate _UpdateComplete;
/// <summary>
/// Occurs before the animations are applied.
/// Use this callback when you want to change the skeleton state before animations are applied on top.
/// </summary>
public event UpdateBonesDelegate BeforeApply { add { _BeforeApply += value; } remove { _BeforeApply -= value; } }
/// <summary>
/// Occurs after the animations are applied and before world space values are resolved.
/// Use this callback when you want to set bone local values.
/// </summary>
public event UpdateBonesDelegate UpdateLocal { add { _UpdateLocal += value; } remove { _UpdateLocal -= value; } }
/// <summary>
/// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
/// Using this callback will cause the world space values to be solved an extra time.
/// Use this callback if want to use bone world space values, and also set bone local values.</summary>
public event UpdateBonesDelegate UpdateWorld { add { _UpdateWorld += value; } remove { _UpdateWorld -= value; } }
/// <summary>
/// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
/// Use this callback if you want to use bone world space values, but don't intend to modify bone local values.
/// This callback can also be used when setting world position and the bone matrix.</summary>
public event UpdateBonesDelegate UpdateComplete { add { _UpdateComplete += value; } remove { _UpdateComplete -= value; } }
#endregion
#region Serialized state and Beginner API
[SerializeField]
[SpineAnimation]
private string _animationName;
/// <summary>
/// Setting this property sets the animation of the skeleton. If invalid, it will store the animation name for the next time the skeleton is properly initialized.
/// Getting this property gets the name of the currently playing animation. If invalid, it will return the last stored animation name set through this property.</summary>
public string AnimationName {
get {
if (!valid) {
return _animationName;
} else {
TrackEntry entry = state.GetCurrent(0);
return entry == null ? null : entry.Animation.Name;
}
}
set {
Initialize(false);
if (_animationName == value) {
TrackEntry entry = state.GetCurrent(0);
if (entry != null && entry.loop == loop)
return;
}
_animationName = value;
if (string.IsNullOrEmpty(value)) {
state.ClearTrack(0);
} else {
var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(value);
if (animationObject != null)
state.SetAnimation(0, animationObject, loop);
}
}
}
/// <summary>Whether or not <see cref="AnimationName"/> should loop. This only applies to the initial animation specified in the inspector, or any subsequent Animations played through .AnimationName. Animations set through state.SetAnimation are unaffected.</summary>
public bool loop;
/// <summary>
/// The rate at which animations progress over time. 1 means 100%. 0.5 means 50%.</summary>
/// <remarks>AnimationState and TrackEntry also have their own timeScale. These are combined multiplicatively.</remarks>
public float timeScale = 1;
#endregion
#region Runtime Instantiation
/// <summary>Adds and prepares a SkeletonAnimation component to a GameObject at runtime.</summary>
/// <returns>The newly instantiated SkeletonAnimation</returns>
public static SkeletonAnimation AddToGameObject (GameObject gameObject, SkeletonDataAsset skeletonDataAsset,
bool quiet = false) {
return SkeletonRenderer.AddSpineComponent<SkeletonAnimation>(gameObject, skeletonDataAsset, quiet);
}
/// <summary>Instantiates a new UnityEngine.GameObject and adds a prepared SkeletonAnimation component to it.</summary>
/// <returns>The newly instantiated SkeletonAnimation component.</returns>
public static SkeletonAnimation NewSkeletonAnimationGameObject (SkeletonDataAsset skeletonDataAsset,
bool quiet = false) {
return SkeletonRenderer.NewSpineGameObject<SkeletonAnimation>(skeletonDataAsset, quiet);
}
#endregion
/// <summary>
/// Clears the previously generated mesh, resets the skeleton's pose, and clears all previously active animations.</summary>
public override void ClearState () {
base.ClearState();
if (state != null) state.ClearTracks();
}
/// <summary>
/// Initialize this component. Attempts to load the SkeletonData and creates the internal Spine objects and buffers.</summary>
/// <param name="overwrite">If set to <c>true</c>, force overwrite an already initialized object.</param>
public override void Initialize (bool overwrite, bool quiet = false) {
if (valid && !overwrite)
return;
base.Initialize(overwrite, quiet);
if (!valid)
return;
state = new Spine.AnimationState(skeletonDataAsset.GetAnimationStateData());
wasUpdatedAfterInit = false;
if (!string.IsNullOrEmpty(_animationName)) {
var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(_animationName);
if (animationObject != null) {
state.SetAnimation(0, animationObject, loop);
#if UNITY_EDITOR
if (!Application.isPlaying)
Update(0f);
#endif
}
}
}
void Update () {
#if UNITY_EDITOR
if (!Application.isPlaying) {
Update(0f);
return;
}
#endif
Update(Time.deltaTime);
}
/// <summary>Progresses the AnimationState according to the given deltaTime, and applies it to the Skeleton. Use Time.deltaTime to update manually. Use deltaTime 0 to update without progressing the time.</summary>
public void Update (float deltaTime) {
if (!valid || state == null)
return;
wasUpdatedAfterInit = true;
if (updateMode < UpdateMode.OnlyAnimationStatus)
return;
UpdateAnimationStatus(deltaTime);
if (updateMode == UpdateMode.OnlyAnimationStatus)
return;
ApplyAnimation();
}
protected void UpdateAnimationStatus (float deltaTime) {
deltaTime *= timeScale;
skeleton.Update(deltaTime);
state.Update(deltaTime);
}
protected void ApplyAnimation () {
if (_BeforeApply != null)
_BeforeApply(this);
if (updateMode != UpdateMode.OnlyEventTimelines)
state.Apply(skeleton);
else
state.ApplyEventTimelinesOnly(skeleton);
if (_UpdateLocal != null)
_UpdateLocal(this);
skeleton.UpdateWorldTransform();
if (_UpdateWorld != null) {
_UpdateWorld(this);
skeleton.UpdateWorldTransform();
}
if (_UpdateComplete != null) {
_UpdateComplete(this);
}
}
public override void LateUpdate () {
// instantiation can happen from Update() after this component, leading to a missing Update() call.
if (!wasUpdatedAfterInit) Update(0);
base.LateUpdate();
}
}
}

View File

@@ -1,10 +0,0 @@
fileFormatVersion: 2
guid: d247ba06193faa74d9335f5481b2b56c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,825 +0,0 @@
/******************************************************************************
* 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_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
#define NEW_PREFAB_SYSTEM
#endif
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Spine.Unity {
#if NEW_PREFAB_SYSTEM
[ExecuteAlways]
#else
[ExecuteInEditMode]
#endif
[RequireComponent(typeof(CanvasRenderer), typeof(RectTransform)), DisallowMultipleComponent]
[AddComponentMenu("Spine/SkeletonGraphic (Unity UI Canvas)")]
[HelpURL("http://esotericsoftware.com/spine-unity#SkeletonGraphic-Component")]
public class SkeletonGraphic : MaskableGraphic, ISkeletonComponent, IAnimationStateComponent, ISkeletonAnimation, IHasSkeletonDataAsset {
#region Inspector
public SkeletonDataAsset skeletonDataAsset;
public SkeletonDataAsset SkeletonDataAsset { get { return skeletonDataAsset; } }
[SpineSkin(dataField:"skeletonDataAsset", defaultAsEmptyString:true)]
public string initialSkinName;
public bool initialFlipX, initialFlipY;
[SpineAnimation(dataField:"skeletonDataAsset")]
public string startingAnimation;
public bool startingLoop;
public float timeScale = 1f;
public bool freeze;
/// <summary>Update mode to optionally limit updates to e.g. only apply animations but not update the mesh.</summary>
public UpdateMode UpdateMode { get { return updateMode; } set { updateMode = value; } }
protected UpdateMode updateMode = UpdateMode.FullUpdate;
/// <summary>Update mode used when the MeshRenderer becomes invisible
/// (when <c>OnBecameInvisible()</c> is called). Update mode is automatically
/// reset to <c>UpdateMode.FullUpdate</c> when the mesh becomes visible again.</summary>
public UpdateMode updateWhenInvisible = UpdateMode.FullUpdate;
public bool unscaledTime;
public bool allowMultipleCanvasRenderers = false;
public List<CanvasRenderer> canvasRenderers = new List<CanvasRenderer>();
protected List<RawImage> rawImages = new List<RawImage>();
protected int usedRenderersCount = 0;
// Submesh Separation
public const string SeparatorPartGameObjectName = "Part";
/// <summary>Slot names used to populate separatorSlots list when the Skeleton is initialized. Changing this after initialization does nothing.</summary>
[SerializeField] [SpineSlot] protected string[] separatorSlotNames = new string[0];
/// <summary>Slots that determine where the render is split. This is used by components such as SkeletonRenderSeparator so that the skeleton can be rendered by two separate renderers on different GameObjects.</summary>
[System.NonSerialized] public readonly List<Slot> separatorSlots = new List<Slot>();
public bool enableSeparatorSlots = false;
[SerializeField] protected List<Transform> separatorParts = new List<Transform>();
public List<Transform> SeparatorParts { get { return separatorParts; } }
public bool updateSeparatorPartLocation = true;
private bool wasUpdatedAfterInit = true;
private Texture baseTexture = null;
#if UNITY_EDITOR
protected override void OnValidate () {
// This handles Scene View preview.
base.OnValidate ();
if (this.IsValid) {
if (skeletonDataAsset == null) {
Clear();
} else if (skeletonDataAsset.skeletonJSON == null) {
Clear();
} else if (skeletonDataAsset.GetSkeletonData(true) != skeleton.data) {
Clear();
Initialize(true);
if (!allowMultipleCanvasRenderers && (skeletonDataAsset.atlasAssets.Length > 1 || skeletonDataAsset.atlasAssets[0].MaterialCount > 1))
Debug.LogError("Unity UI does not support multiple textures per Renderer. Please enable 'Advanced - Multiple CanvasRenderers' to generate the required CanvasRenderer GameObjects. Otherwise your skeleton will not be rendered correctly.", this);
} else {
if (freeze) return;
if (!string.IsNullOrEmpty(initialSkinName)) {
var skin = skeleton.data.FindSkin(initialSkinName);
if (skin != null) {
if (skin == skeleton.data.defaultSkin)
skeleton.SetSkin((Skin)null);
else
skeleton.SetSkin(skin);
}
}
// Only provide visual feedback to inspector changes in Unity Editor Edit mode.
if (!Application.isPlaying) {
skeleton.ScaleX = this.initialFlipX ? -1 : 1;
skeleton.ScaleY = this.initialFlipY ? -1 : 1;
state.ClearTrack(0);
skeleton.SetToSetupPose();
if (!string.IsNullOrEmpty(startingAnimation)) {
state.SetAnimation(0, startingAnimation, startingLoop);
Update(0f);
}
}
}
} else {
// Under some circumstances (e.g. sometimes on the first import) OnValidate is called
// before SpineEditorUtilities.ImportSpineContent, causing an unnecessary exception.
// The (skeletonDataAsset.skeletonJSON != null) condition serves to prevent this exception.
if (skeletonDataAsset != null && skeletonDataAsset.skeletonJSON != null)
Initialize(true);
}
}
protected override void Reset () {
base.Reset();
if (material == null || material.shader != Shader.Find("Spine/SkeletonGraphic"))
Debug.LogWarning("SkeletonGraphic works best with the SkeletonGraphic material.");
}
#endif
#endregion
#region Runtime Instantiation
/// <summary>Create a new GameObject with a SkeletonGraphic component.</summary>
/// <param name="material">Material for the canvas renderer to use. Usually, the default SkeletonGraphic material will work.</param>
public static SkeletonGraphic NewSkeletonGraphicGameObject (SkeletonDataAsset skeletonDataAsset, Transform parent, Material material) {
var sg = SkeletonGraphic.AddSkeletonGraphicComponent(new GameObject("New Spine GameObject"), skeletonDataAsset, material);
if (parent != null) sg.transform.SetParent(parent, false);
return sg;
}
/// <summary>Add a SkeletonGraphic component to a GameObject.</summary>
/// <param name="material">Material for the canvas renderer to use. Usually, the default SkeletonGraphic material will work.</param>
public static SkeletonGraphic AddSkeletonGraphicComponent (GameObject gameObject, SkeletonDataAsset skeletonDataAsset, Material material) {
var c = gameObject.AddComponent<SkeletonGraphic>();
if (skeletonDataAsset != null) {
c.material = material;
c.skeletonDataAsset = skeletonDataAsset;
c.Initialize(false);
}
return c;
}
#endregion
#region Overrides
[System.NonSerialized] readonly Dictionary<Texture, Texture> customTextureOverride = new Dictionary<Texture, Texture>();
/// <summary>Use this Dictionary to override a Texture with a different Texture.</summary>
public Dictionary<Texture, Texture> CustomTextureOverride { get { return customTextureOverride; } }
[System.NonSerialized] readonly Dictionary<Texture, Material> customMaterialOverride = new Dictionary<Texture, Material>();
/// <summary>Use this Dictionary to override the Material where the Texture was used at the original atlas.</summary>
public Dictionary<Texture, Material> CustomMaterialOverride { get { return customMaterialOverride; } }
// This is used by the UI system to determine what to put in the MaterialPropertyBlock.
Texture overrideTexture;
public Texture OverrideTexture {
get { return overrideTexture; }
set {
overrideTexture = value;
canvasRenderer.SetTexture(this.mainTexture); // Refresh canvasRenderer's texture. Make sure it handles null.
}
}
#endregion
#region Internals
public override Texture mainTexture {
get {
if (overrideTexture != null) return overrideTexture;
return baseTexture;
}
}
protected override void Awake () {
base.Awake ();
this.onCullStateChanged.AddListener(OnCullStateChanged);
SyncRawImagesWithCanvasRenderers();
if (!this.IsValid) {
#if UNITY_EDITOR
// workaround for special import case of open scene where OnValidate and Awake are
// called in wrong order, before setup of Spine assets.
if (!Application.isPlaying) {
if (this.skeletonDataAsset != null && this.skeletonDataAsset.skeletonJSON == null)
return;
}
#endif
Initialize(false);
Rebuild(CanvasUpdate.PreRender);
}
}
protected override void OnDestroy () {
Clear();
base.OnDestroy();
}
public override void Rebuild (CanvasUpdate update) {
base.Rebuild(update);
if (canvasRenderer.cull) return;
if (update == CanvasUpdate.PreRender) UpdateMesh(keepRendererCount : true);
if (allowMultipleCanvasRenderers) canvasRenderer.Clear();
}
protected override void OnDisable () {
base.OnDisable();
foreach (var canvasRenderer in canvasRenderers) {
canvasRenderer.Clear();
}
}
public virtual void Update () {
#if UNITY_EDITOR
if (!Application.isPlaying) {
Update(0f);
return;
}
#endif
if (freeze) return;
Update(unscaledTime ? Time.unscaledDeltaTime : Time.deltaTime);
}
public virtual void Update (float deltaTime) {
if (!this.IsValid) return;
wasUpdatedAfterInit = true;
if (updateMode < UpdateMode.OnlyAnimationStatus)
return;
UpdateAnimationStatus(deltaTime);
if (updateMode == UpdateMode.OnlyAnimationStatus)
return;
ApplyAnimation();
}
protected void SyncRawImagesWithCanvasRenderers () {
rawImages.Clear();
foreach (var canvasRenderer in canvasRenderers) {
var rawImage = canvasRenderer.GetComponent<RawImage>();
if (rawImage == null) {
rawImage = canvasRenderer.gameObject.AddComponent<RawImage>();
rawImage.maskable = this.maskable;
rawImage.raycastTarget = false;
}
rawImages.Add(rawImage);
}
}
protected void UpdateAnimationStatus (float deltaTime) {
deltaTime *= timeScale;
skeleton.Update(deltaTime);
state.Update(deltaTime);
}
protected void ApplyAnimation () {
if (BeforeApply != null)
BeforeApply(this);
if (updateMode != UpdateMode.OnlyEventTimelines)
state.Apply(skeleton);
else
state.ApplyEventTimelinesOnly(skeleton);
if (UpdateLocal != null)
UpdateLocal(this);
skeleton.UpdateWorldTransform();
if (UpdateWorld != null) {
UpdateWorld(this);
skeleton.UpdateWorldTransform();
}
if (UpdateComplete != null)
UpdateComplete(this);
}
public void LateUpdate () {
// instantiation can happen from Update() after this component, leading to a missing Update() call.
if (!wasUpdatedAfterInit) Update(0);
if (freeze) return;
if (updateMode != UpdateMode.FullUpdate) return;
UpdateMesh();
}
protected void OnCullStateChanged (bool culled) {
if (culled)
OnBecameInvisible();
else
OnBecameVisible();
}
public void OnBecameVisible () {
updateMode = UpdateMode.FullUpdate;
}
public void OnBecameInvisible () {
updateMode = updateWhenInvisible;
}
public void ReapplySeparatorSlotNames () {
if (!IsValid)
return;
separatorSlots.Clear();
for (int i = 0, n = separatorSlotNames.Length; i < n; i++) {
string slotName = separatorSlotNames[i];
if (slotName == "")
continue;
var slot = skeleton.FindSlot(slotName);
if (slot != null) {
separatorSlots.Add(slot);
}
#if UNITY_EDITOR
else
{
Debug.LogWarning(slotName + " is not a slot in " + skeletonDataAsset.skeletonJSON.name);
}
#endif
}
UpdateSeparatorPartParents();
}
#endregion
#region API
protected Skeleton skeleton;
public Skeleton Skeleton {
get {
Initialize(false);
return skeleton;
}
set {
skeleton = value;
}
}
public SkeletonData SkeletonData { get { return skeleton == null ? null : skeleton.data; } }
public bool IsValid { get { return skeleton != null; } }
public delegate void SkeletonRendererDelegate (SkeletonGraphic skeletonGraphic);
/// <summary>OnRebuild is raised after the Skeleton is successfully initialized.</summary>
public event SkeletonRendererDelegate OnRebuild;
/// <summary>OnMeshAndMaterialsUpdated is at the end of LateUpdate after the Mesh and
/// all materials have been updated.</summary>
public event SkeletonRendererDelegate OnMeshAndMaterialsUpdated;
protected Spine.AnimationState state;
public Spine.AnimationState AnimationState {
get {
Initialize(false);
return state;
}
}
[SerializeField] protected Spine.Unity.MeshGenerator meshGenerator = new MeshGenerator();
public Spine.Unity.MeshGenerator MeshGenerator { get { return this.meshGenerator; } }
DoubleBuffered<Spine.Unity.MeshRendererBuffers.SmartMesh> meshBuffers;
SkeletonRendererInstruction currentInstructions = new SkeletonRendererInstruction();
readonly ExposedList<Mesh> meshes = new ExposedList<Mesh>();
public Mesh GetLastMesh () {
return meshBuffers.GetCurrent().mesh;
}
public bool MatchRectTransformWithBounds () {
UpdateMesh();
if (!this.allowMultipleCanvasRenderers)
return MatchRectTransformSingleRenderer();
else
return MatchRectTransformMultipleRenderers();
}
protected bool MatchRectTransformSingleRenderer () {
Mesh mesh = this.GetLastMesh();
if (mesh == null) {
return false;
}
if (mesh.vertexCount == 0) {
this.rectTransform.sizeDelta = new Vector2(50f, 50f);
this.rectTransform.pivot = new Vector2(0.5f, 0.5f);
return false;
}
mesh.RecalculateBounds();
SetRectTransformBounds(mesh.bounds);
return true;
}
protected bool MatchRectTransformMultipleRenderers () {
bool anyBoundsAdded = false;
Bounds combinedBounds = new Bounds();
for (int i = 0; i < canvasRenderers.Count; ++i) {
var canvasRenderer = canvasRenderers[i];
if (!canvasRenderer.gameObject.activeSelf)
continue;
Mesh mesh = meshes.Items[i];
if (mesh == null || mesh.vertexCount == 0)
continue;
mesh.RecalculateBounds();
var bounds = mesh.bounds;
if (anyBoundsAdded)
combinedBounds.Encapsulate(bounds);
else {
anyBoundsAdded = true;
combinedBounds = bounds;
}
}
if (!anyBoundsAdded) {
this.rectTransform.sizeDelta = new Vector2(50f, 50f);
this.rectTransform.pivot = new Vector2(0.5f, 0.5f);
return false;
}
SetRectTransformBounds(combinedBounds);
return true;
}
private void SetRectTransformBounds (Bounds combinedBounds) {
var size = combinedBounds.size;
var center = combinedBounds.center;
var p = new Vector2(
0.5f - (center.x / size.x),
0.5f - (center.y / size.y)
);
this.rectTransform.sizeDelta = size;
this.rectTransform.pivot = p;
}
public event UpdateBonesDelegate BeforeApply;
public event UpdateBonesDelegate UpdateLocal;
public event UpdateBonesDelegate UpdateWorld;
public event UpdateBonesDelegate UpdateComplete;
/// <summary> Occurs after the vertex data populated every frame, before the vertices are pushed into the mesh.</summary>
public event Spine.Unity.MeshGeneratorDelegate OnPostProcessVertices;
public void Clear () {
skeleton = null;
canvasRenderer.Clear();
for (int i = 0; i < canvasRenderers.Count; ++i)
canvasRenderers[i].Clear();
DestroyMeshes();
DisposeMeshBuffers();
}
public void TrimRenderers () {
var newList = new List<CanvasRenderer>();
foreach (var canvasRenderer in canvasRenderers) {
if (canvasRenderer.gameObject.activeSelf) {
newList.Add(canvasRenderer);
}
else {
if (Application.isEditor && !Application.isPlaying)
DestroyImmediate(canvasRenderer.gameObject);
else
Destroy(canvasRenderer.gameObject);
}
}
canvasRenderers = newList;
SyncRawImagesWithCanvasRenderers();
}
public void Initialize (bool overwrite) {
if (this.IsValid && !overwrite) return;
if (this.skeletonDataAsset == null) return;
var skeletonData = this.skeletonDataAsset.GetSkeletonData(false);
if (skeletonData == null) return;
if (skeletonDataAsset.atlasAssets.Length <= 0 || skeletonDataAsset.atlasAssets[0].MaterialCount <= 0) return;
this.state = new Spine.AnimationState(skeletonDataAsset.GetAnimationStateData());
if (state == null) {
Clear();
return;
}
this.skeleton = new Skeleton(skeletonData) {
ScaleX = this.initialFlipX ? -1 : 1,
ScaleY = this.initialFlipY ? -1 : 1
};
InitMeshBuffers();
baseTexture = skeletonDataAsset.atlasAssets[0].PrimaryMaterial.mainTexture;
canvasRenderer.SetTexture(this.mainTexture); // Needed for overwriting initializations.
// Set the initial Skin and Animation
if (!string.IsNullOrEmpty(initialSkinName))
skeleton.SetSkin(initialSkinName);
separatorSlots.Clear();
for (int i = 0; i < separatorSlotNames.Length; i++)
separatorSlots.Add(skeleton.FindSlot(separatorSlotNames[i]));
wasUpdatedAfterInit = false;
if (!string.IsNullOrEmpty(startingAnimation)) {
var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(startingAnimation);
if (animationObject != null) {
state.SetAnimation(0, animationObject, startingLoop);
#if UNITY_EDITOR
if (!Application.isPlaying)
Update(0f);
#endif
}
}
if (OnRebuild != null)
OnRebuild(this);
}
public void UpdateMesh (bool keepRendererCount = false) {
if (!this.IsValid) return;
skeleton.SetColor(this.color);
var currentInstructions = this.currentInstructions;
if (!this.allowMultipleCanvasRenderers) {
UpdateMeshSingleCanvasRenderer();
}
else {
UpdateMeshMultipleCanvasRenderers(currentInstructions, keepRendererCount);
}
if (OnMeshAndMaterialsUpdated != null)
OnMeshAndMaterialsUpdated(this);
}
public bool HasMultipleSubmeshInstructions () {
if (!IsValid)
return false;
return MeshGenerator.RequiresMultipleSubmeshesByDrawOrder(skeleton);
}
#endregion
protected void InitMeshBuffers () {
if (meshBuffers != null) {
meshBuffers.GetNext().Clear();
meshBuffers.GetNext().Clear();
}
else {
meshBuffers = new DoubleBuffered<MeshRendererBuffers.SmartMesh>();
}
}
protected void DisposeMeshBuffers () {
if (meshBuffers != null) {
meshBuffers.GetNext().Dispose();
meshBuffers.GetNext().Dispose();
meshBuffers = null;
}
}
protected void UpdateMeshSingleCanvasRenderer () {
if (canvasRenderers.Count > 0)
DisableUnusedCanvasRenderers(usedCount : 0);
var smartMesh = meshBuffers.GetNext();
MeshGenerator.GenerateSingleSubmeshInstruction(currentInstructions, skeleton, null);
bool updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, smartMesh.instructionUsed);
meshGenerator.Begin();
if (currentInstructions.hasActiveClipping && currentInstructions.submeshInstructions.Count > 0) {
meshGenerator.AddSubmesh(currentInstructions.submeshInstructions.Items[0], updateTriangles);
}
else {
meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles);
}
if (canvas != null) meshGenerator.ScaleVertexData(canvas.referencePixelsPerUnit);
if (OnPostProcessVertices != null) OnPostProcessVertices.Invoke(this.meshGenerator.Buffers);
var mesh = smartMesh.mesh;
meshGenerator.FillVertexData(mesh);
if (updateTriangles) meshGenerator.FillTriangles(mesh);
meshGenerator.FillLateVertexData(mesh);
canvasRenderer.SetMesh(mesh);
smartMesh.instructionUsed.Set(currentInstructions);
if (currentInstructions.submeshInstructions.Count > 0) {
var material = currentInstructions.submeshInstructions.Items[0].material;
if (material != null && baseTexture != material.mainTexture) {
baseTexture = material.mainTexture;
if (overrideTexture == null)
canvasRenderer.SetTexture(this.mainTexture);
}
}
//this.UpdateMaterial(); // note: This would allocate memory.
usedRenderersCount = 0;
}
protected void UpdateMeshMultipleCanvasRenderers (SkeletonRendererInstruction currentInstructions, bool keepRendererCount) {
MeshGenerator.GenerateSkeletonRendererInstruction(currentInstructions, skeleton, null,
enableSeparatorSlots ? separatorSlots : null,
enableSeparatorSlots ? separatorSlots.Count > 0 : false,
false);
int submeshCount = currentInstructions.submeshInstructions.Count;
if (keepRendererCount && submeshCount != usedRenderersCount)
return;
EnsureCanvasRendererCount(submeshCount);
EnsureMeshesCount(submeshCount);
EnsureSeparatorPartCount();
var c = canvas;
float scale = (c == null) ? 100 : c.referencePixelsPerUnit;
// Generate meshes.
var meshesItems = meshes.Items;
bool useOriginalTextureAndMaterial = (customMaterialOverride.Count == 0 && customTextureOverride.Count == 0);
int separatorSlotGroupIndex = 0;
Transform parent = this.separatorSlots.Count == 0 ? this.transform : this.separatorParts[0];
if (updateSeparatorPartLocation) {
for (int p = 0; p < this.separatorParts.Count; ++p) {
separatorParts[p].position = this.transform.position;
separatorParts[p].rotation = this.transform.rotation;
}
}
int targetSiblingIndex = 0;
for (int i = 0; i < submeshCount; i++) {
var submeshInstructionItem = currentInstructions.submeshInstructions.Items[i];
meshGenerator.Begin();
meshGenerator.AddSubmesh(submeshInstructionItem);
var targetMesh = meshesItems[i];
meshGenerator.ScaleVertexData(scale);
if (OnPostProcessVertices != null) OnPostProcessVertices.Invoke(this.meshGenerator.Buffers);
meshGenerator.FillVertexData(targetMesh);
meshGenerator.FillTriangles(targetMesh);
meshGenerator.FillLateVertexData(targetMesh);
var submeshMaterial = submeshInstructionItem.material;
var canvasRenderer = canvasRenderers[i];
if (i >= usedRenderersCount)
canvasRenderer.gameObject.SetActive(true);
canvasRenderer.SetMesh(targetMesh);
canvasRenderer.materialCount = 1;
if (canvasRenderer.transform.parent != parent.transform) {
canvasRenderer.transform.SetParent(parent.transform, false);
canvasRenderer.transform.localPosition = Vector3.zero;
}
canvasRenderer.transform.SetSiblingIndex(targetSiblingIndex++);
if (submeshInstructionItem.forceSeparate) {
targetSiblingIndex = 0;
parent = separatorParts[++separatorSlotGroupIndex];
}
if (useOriginalTextureAndMaterial)
canvasRenderer.SetMaterial(this.materialForRendering, submeshMaterial.mainTexture);
else {
var originalTexture = submeshMaterial.mainTexture;
Material usedMaterial;
Texture usedTexture;
if (!customMaterialOverride.TryGetValue(originalTexture, out usedMaterial))
usedMaterial = material;
if (!customTextureOverride.TryGetValue(originalTexture, out usedTexture))
usedTexture = originalTexture;
canvasRenderer.SetMaterial(usedMaterial, usedTexture);
}
}
DisableUnusedCanvasRenderers(usedCount : submeshCount);
usedRenderersCount = submeshCount;
}
protected void EnsureCanvasRendererCount (int targetCount) {
#if UNITY_EDITOR
RemoveNullCanvasRenderers();
#endif
int currentCount = canvasRenderers.Count;
for (int i = currentCount; i < targetCount; ++i) {
var go = new GameObject(string.Format("Renderer{0}", i), typeof(RectTransform));
go.transform.SetParent(this.transform, false);
go.transform.localPosition = Vector3.zero;
var canvasRenderer = go.AddComponent<CanvasRenderer>();
canvasRenderers.Add(canvasRenderer);
var rawImage = go.AddComponent<RawImage>();
rawImage.maskable = this.maskable;
rawImage.raycastTarget = false;
rawImages.Add(rawImage);
}
}
protected void DisableUnusedCanvasRenderers (int usedCount) {
#if UNITY_EDITOR
RemoveNullCanvasRenderers();
#endif
for (int i = usedCount; i < canvasRenderers.Count; i++) {
canvasRenderers[i].Clear();
canvasRenderers[i].gameObject.SetActive(false);
}
}
#if UNITY_EDITOR
private void RemoveNullCanvasRenderers () {
if (Application.isEditor && !Application.isPlaying) {
for (int i = canvasRenderers.Count - 1; i >= 0; --i) {
if (canvasRenderers[i] == null) {
canvasRenderers.RemoveAt(i);
}
}
}
}
#endif
protected void EnsureMeshesCount (int targetCount) {
int oldCount = meshes.Count;
meshes.EnsureCapacity(targetCount);
for (int i = oldCount; i < targetCount; i++)
meshes.Add(SpineMesh.NewSkeletonMesh());
}
protected void DestroyMeshes () {
foreach (var mesh in meshes) {
#if UNITY_EDITOR
if (Application.isEditor && !Application.isPlaying)
UnityEngine.Object.DestroyImmediate(mesh);
else
UnityEngine.Object.Destroy(mesh);
#else
UnityEngine.Object.Destroy(mesh);
#endif
}
meshes.Clear();
}
protected void EnsureSeparatorPartCount () {
#if UNITY_EDITOR
RemoveNullSeparatorParts();
#endif
int targetCount = separatorSlots.Count + 1;
if (targetCount == 1)
return;
#if UNITY_EDITOR
if (Application.isEditor && !Application.isPlaying) {
for (int i = separatorParts.Count-1; i >= 0; --i) {
if (separatorParts[i] == null) {
separatorParts.RemoveAt(i);
}
}
}
#endif
int currentCount = separatorParts.Count;
for (int i = currentCount; i < targetCount; ++i) {
var go = new GameObject(string.Format("{0}[{1}]", SeparatorPartGameObjectName, i), typeof(RectTransform));
go.transform.SetParent(this.transform, false);
go.transform.localPosition = Vector3.zero;
separatorParts.Add(go.transform);
}
}
protected void UpdateSeparatorPartParents () {
int usedCount = separatorSlots.Count + 1;
if (usedCount == 1) {
usedCount = 0; // placed directly at the SkeletonGraphic parent
for (int i = 0; i < canvasRenderers.Count; ++i) {
var canvasRenderer = canvasRenderers[i];
if (canvasRenderer.transform.parent.name.Contains(SeparatorPartGameObjectName)) {
canvasRenderer.transform.SetParent(this.transform, false);
canvasRenderer.transform.localPosition = Vector3.zero;
}
}
}
for (int i = 0; i < separatorParts.Count; ++i) {
bool isUsed = i < usedCount;
separatorParts[i].gameObject.SetActive(isUsed);
}
}
#if UNITY_EDITOR
private void RemoveNullSeparatorParts () {
if (Application.isEditor && !Application.isPlaying) {
for (int i = separatorParts.Count - 1; i >= 0; --i) {
if (separatorParts[i] == null) {
separatorParts.RemoveAt(i);
}
}
}
}
#endif
}
}

View File

@@ -1,14 +0,0 @@
fileFormatVersion: 2
guid: d85b887af7e6c3f45a2e2d2920d641bc
timeCreated: 1455576193
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences:
- m_Material: {fileID: 2100000, guid: b66cf7a186d13054989b33a5c90044e4, type: 2}
- skeletonDataAsset: {instanceID: 0}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,661 +0,0 @@
/******************************************************************************
* 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;
namespace Spine.Unity {
[RequireComponent(typeof(Animator))]
[HelpURL("http://esotericsoftware.com/spine-unity#SkeletonMecanim-Component")]
public class SkeletonMecanim : SkeletonRenderer, ISkeletonAnimation {
[SerializeField] protected MecanimTranslator translator;
public MecanimTranslator Translator { get { return translator; } }
private bool wasUpdatedAfterInit = true;
#region Bone Callbacks (ISkeletonAnimation)
protected event UpdateBonesDelegate _BeforeApply;
protected event UpdateBonesDelegate _UpdateLocal;
protected event UpdateBonesDelegate _UpdateWorld;
protected event UpdateBonesDelegate _UpdateComplete;
/// <summary>
/// Occurs before the animations are applied.
/// Use this callback when you want to change the skeleton state before animations are applied on top.
/// </summary>
public event UpdateBonesDelegate BeforeApply { add { _BeforeApply += value; } remove { _BeforeApply -= value; } }
/// <summary>
/// Occurs after the animations are applied and before world space values are resolved.
/// Use this callback when you want to set bone local values.</summary>
public event UpdateBonesDelegate UpdateLocal { add { _UpdateLocal += value; } remove { _UpdateLocal -= value; } }
/// <summary>
/// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
/// Using this callback will cause the world space values to be solved an extra time.
/// Use this callback if want to use bone world space values, and also set bone local values.</summary>
public event UpdateBonesDelegate UpdateWorld { add { _UpdateWorld += value; } remove { _UpdateWorld -= value; } }
/// <summary>
/// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
/// Use this callback if you want to use bone world space values, but don't intend to modify bone local values.
/// This callback can also be used when setting world position and the bone matrix.</summary>
public event UpdateBonesDelegate UpdateComplete { add { _UpdateComplete += value; } remove { _UpdateComplete -= value; } }
#endregion
public override void Initialize (bool overwrite, bool quiet = false) {
if (valid && !overwrite)
return;
base.Initialize(overwrite, quiet);
if (!valid)
return;
if (translator == null) translator = new MecanimTranslator();
translator.Initialize(GetComponent<Animator>(), this.skeletonDataAsset);
wasUpdatedAfterInit = false;
}
public void Update () {
if (!valid) return;
wasUpdatedAfterInit = true;
// animation status is kept by Mecanim Animator component
if (updateMode <= UpdateMode.OnlyAnimationStatus)
return;
ApplyAnimation();
}
protected void ApplyAnimation () {
if (_BeforeApply != null)
_BeforeApply(this);
#if UNITY_EDITOR
var translatorAnimator = translator.Animator;
if (translatorAnimator != null && !translatorAnimator.isInitialized)
translatorAnimator.Rebind();
if (Application.isPlaying) {
translator.Apply(skeleton);
}
else {
if (translatorAnimator != null && translatorAnimator.isInitialized &&
translatorAnimator.isActiveAndEnabled && translatorAnimator.runtimeAnimatorController != null) {
// Note: Rebind is required to prevent warning "Animator is not playing an AnimatorController" with prefabs
translatorAnimator.Rebind();
translator.Apply(skeleton);
}
}
#else
translator.Apply(skeleton);
#endif
// UpdateWorldTransform and Bone Callbacks
{
if (_UpdateLocal != null)
_UpdateLocal(this);
skeleton.UpdateWorldTransform();
if (_UpdateWorld != null) {
_UpdateWorld(this);
skeleton.UpdateWorldTransform();
}
if (_UpdateComplete != null)
_UpdateComplete(this);
}
}
public override void LateUpdate () {
// instantiation can happen from Update() after this component, leading to a missing Update() call.
if (!wasUpdatedAfterInit) Update();
base.LateUpdate();
}
[System.Serializable]
public class MecanimTranslator {
const float WeightEpsilon = 0.0001f;
#region Inspector
public bool autoReset = true;
public bool useCustomMixMode = true;
public MixMode[] layerMixModes = new MixMode[0];
public MixBlend[] layerBlendModes = new MixBlend[0];
#endregion
public delegate void OnClipAppliedDelegate (Spine.Animation clip, int layerIndex, float weight,
float time, float lastTime, bool playsBackward);
protected event OnClipAppliedDelegate _OnClipApplied;
public event OnClipAppliedDelegate OnClipApplied { add { _OnClipApplied += value; } remove { _OnClipApplied -= value; } }
public enum MixMode { AlwaysMix, MixNext, Hard }
readonly Dictionary<int, Spine.Animation> animationTable = new Dictionary<int, Spine.Animation>(IntEqualityComparer.Instance);
readonly Dictionary<AnimationClip, int> clipNameHashCodeTable = new Dictionary<AnimationClip, int>(AnimationClipEqualityComparer.Instance);
readonly List<Animation> previousAnimations = new List<Animation>();
protected class ClipInfos {
public bool isInterruptionActive = false;
public bool isLastFrameOfInterruption = false;
public int clipInfoCount = 0;
public int nextClipInfoCount = 0;
public int interruptingClipInfoCount = 0;
public readonly List<AnimatorClipInfo> clipInfos = new List<AnimatorClipInfo>();
public readonly List<AnimatorClipInfo> nextClipInfos = new List<AnimatorClipInfo>();
public readonly List<AnimatorClipInfo> interruptingClipInfos = new List<AnimatorClipInfo>();
public AnimatorStateInfo stateInfo;
public AnimatorStateInfo nextStateInfo;
public AnimatorStateInfo interruptingStateInfo;
public float interruptingClipTimeAddition = 0;
}
protected ClipInfos[] layerClipInfos = new ClipInfos[0];
Animator animator;
public Animator Animator { get { return this.animator; } }
public int MecanimLayerCount {
get {
if (!animator)
return 0;
return animator.layerCount;
}
}
public string[] MecanimLayerNames {
get {
if (!animator)
return new string[0];
string[] layerNames = new string[animator.layerCount];
for (int i = 0; i < animator.layerCount; ++i) {
layerNames[i] = animator.GetLayerName(i);
}
return layerNames;
}
}
public void Initialize(Animator animator, SkeletonDataAsset skeletonDataAsset) {
this.animator = animator;
previousAnimations.Clear();
animationTable.Clear();
var data = skeletonDataAsset.GetSkeletonData(true);
foreach (var a in data.Animations)
animationTable.Add(a.Name.GetHashCode(), a);
clipNameHashCodeTable.Clear();
ClearClipInfosForLayers();
}
private bool ApplyAnimation (Skeleton skeleton, AnimatorClipInfo info, AnimatorStateInfo stateInfo,
int layerIndex, float layerWeight, MixBlend layerBlendMode, bool useClipWeight1 = false) {
float weight = info.weight * layerWeight;
if (weight < WeightEpsilon)
return false;
var clip = GetAnimation(info.clip);
if (clip == null)
return false;
var time = AnimationTime(stateInfo.normalizedTime, info.clip.length,
info.clip.isLooping, stateInfo.speed < 0);
weight = useClipWeight1 ? layerWeight : weight;
clip.Apply(skeleton, 0, time, info.clip.isLooping, null,
weight, layerBlendMode, MixDirection.In);
if (_OnClipApplied != null)
OnClipAppliedCallback(clip, stateInfo, layerIndex, time, info.clip.isLooping, weight);
return true;
}
private bool ApplyInterruptionAnimation (Skeleton skeleton,
bool interpolateWeightTo1, AnimatorClipInfo info, AnimatorStateInfo stateInfo,
int layerIndex, float layerWeight, MixBlend layerBlendMode, float interruptingClipTimeAddition,
bool useClipWeight1 = false) {
float clipWeight = interpolateWeightTo1 ? (info.weight + 1.0f) * 0.5f : info.weight;
float weight = clipWeight * layerWeight;
if (weight < WeightEpsilon)
return false;
var clip = GetAnimation(info.clip);
if (clip == null)
return false;
var time = AnimationTime(stateInfo.normalizedTime + interruptingClipTimeAddition,
info.clip.length, stateInfo.speed < 0);
weight = useClipWeight1 ? layerWeight : weight;
clip.Apply(skeleton, 0, time, info.clip.isLooping, null,
weight, layerBlendMode, MixDirection.In);
if (_OnClipApplied != null) {
OnClipAppliedCallback(clip, stateInfo, layerIndex, time, info.clip.isLooping, weight);
}
return true;
}
private void OnClipAppliedCallback (Spine.Animation clip, AnimatorStateInfo stateInfo,
int layerIndex, float time, bool isLooping, float weight) {
float speedFactor = stateInfo.speedMultiplier * stateInfo.speed;
float lastTime = time - (Time.deltaTime * speedFactor);
if (isLooping && clip.duration != 0) {
time %= clip.duration;
lastTime %= clip.duration;
}
_OnClipApplied(clip, layerIndex, weight, time, lastTime, speedFactor < 0);
}
public void Apply (Skeleton skeleton) {
#if UNITY_EDITOR
if (!Application.isPlaying) {
GetLayerBlendModes();
}
#endif
if (layerMixModes.Length < animator.layerCount) {
int oldSize = layerMixModes.Length;
System.Array.Resize<MixMode>(ref layerMixModes, animator.layerCount);
for (int layer = oldSize; layer < animator.layerCount; ++layer) {
bool isAdditiveLayer = false;
if (layer < layerBlendModes.Length)
isAdditiveLayer = layerBlendModes[layer] == MixBlend.Add;
layerMixModes[layer] = isAdditiveLayer ? MixMode.AlwaysMix : MixMode.MixNext;
}
}
InitClipInfosForLayers();
for (int layer = 0, n = animator.layerCount; layer < n; layer++) {
GetStateUpdatesFromAnimator(layer);
}
// Clear Previous
if (autoReset) {
var previousAnimations = this.previousAnimations;
for (int i = 0, n = previousAnimations.Count; i < n; i++)
previousAnimations[i].SetKeyedItemsToSetupPose(skeleton);
previousAnimations.Clear();
for (int layer = 0, n = animator.layerCount; layer < n; layer++) {
float layerWeight = (layer == 0) ? 1 : animator.GetLayerWeight(layer); // Animator.GetLayerWeight always returns 0 on the first layer. Should be interpreted as 1.
if (layerWeight <= 0) continue;
AnimatorStateInfo nextStateInfo = animator.GetNextAnimatorStateInfo(layer);
bool hasNext = nextStateInfo.fullPathHash != 0;
int clipInfoCount, nextClipInfoCount, interruptingClipInfoCount;
IList<AnimatorClipInfo> clipInfo, nextClipInfo, interruptingClipInfo;
bool isInterruptionActive, shallInterpolateWeightTo1;
GetAnimatorClipInfos(layer, out isInterruptionActive, out clipInfoCount, out nextClipInfoCount, out interruptingClipInfoCount,
out clipInfo, out nextClipInfo, out interruptingClipInfo, out shallInterpolateWeightTo1);
for (int c = 0; c < clipInfoCount; c++) {
var info = clipInfo[c];
float weight = info.weight * layerWeight; if (weight < WeightEpsilon) continue;
var clip = GetAnimation(info.clip);
if (clip != null)
previousAnimations.Add(clip);
}
if (hasNext) {
for (int c = 0; c < nextClipInfoCount; c++) {
var info = nextClipInfo[c];
float weight = info.weight * layerWeight; if (weight < WeightEpsilon) continue;
var clip = GetAnimation(info.clip);
if (clip != null)
previousAnimations.Add(clip);
}
}
if (isInterruptionActive) {
for (int c = 0; c < interruptingClipInfoCount; c++)
{
var info = interruptingClipInfo[c];
float clipWeight = shallInterpolateWeightTo1 ? (info.weight + 1.0f) * 0.5f : info.weight;
float weight = clipWeight * layerWeight; if (weight < WeightEpsilon) continue;
var clip = GetAnimation(info.clip);
if (clip != null)
previousAnimations.Add(clip);
}
}
}
}
// Apply
for (int layer = 0, n = animator.layerCount; layer < n; layer++) {
float layerWeight = (layer == 0) ? 1 : animator.GetLayerWeight(layer); // Animator.GetLayerWeight always returns 0 on the first layer. Should be interpreted as 1.
bool isInterruptionActive;
AnimatorStateInfo stateInfo;
AnimatorStateInfo nextStateInfo;
AnimatorStateInfo interruptingStateInfo;
float interruptingClipTimeAddition;
GetAnimatorStateInfos(layer, out isInterruptionActive, out stateInfo, out nextStateInfo, out interruptingStateInfo, out interruptingClipTimeAddition);
bool hasNext = nextStateInfo.fullPathHash != 0;
int clipInfoCount, nextClipInfoCount, interruptingClipInfoCount;
IList<AnimatorClipInfo> clipInfo, nextClipInfo, interruptingClipInfo;
bool interpolateWeightTo1;
GetAnimatorClipInfos(layer, out isInterruptionActive, out clipInfoCount, out nextClipInfoCount, out interruptingClipInfoCount,
out clipInfo, out nextClipInfo, out interruptingClipInfo, out interpolateWeightTo1);
MixBlend layerBlendMode = (layer < layerBlendModes.Length) ? layerBlendModes[layer] : MixBlend.Replace;
MixMode mode = GetMixMode(layer, layerBlendMode);
if (mode == MixMode.AlwaysMix) {
// Always use Mix instead of Applying the first non-zero weighted clip.
for (int c = 0; c < clipInfoCount; c++) {
ApplyAnimation(skeleton, clipInfo[c], stateInfo, layer, layerWeight, layerBlendMode);
}
if (hasNext) {
for (int c = 0; c < nextClipInfoCount; c++) {
ApplyAnimation(skeleton, nextClipInfo[c], nextStateInfo, layer, layerWeight, layerBlendMode);
}
}
if (isInterruptionActive) {
for (int c = 0; c < interruptingClipInfoCount; c++)
{
ApplyInterruptionAnimation(skeleton, interpolateWeightTo1,
interruptingClipInfo[c], interruptingStateInfo,
layer, layerWeight, layerBlendMode, interruptingClipTimeAddition);
}
}
} else { // case MixNext || Hard
// Apply first non-zero weighted clip
int c = 0;
for (; c < clipInfoCount; c++) {
if (!ApplyAnimation(skeleton, clipInfo[c], stateInfo, layer, layerWeight, layerBlendMode, useClipWeight1:true))
continue;
++c; break;
}
// Mix the rest
for (; c < clipInfoCount; c++) {
ApplyAnimation(skeleton, clipInfo[c], stateInfo, layer, layerWeight, layerBlendMode);
}
c = 0;
if (hasNext) {
// Apply next clip directly instead of mixing (ie: no crossfade, ignores mecanim transition weights)
if (mode == MixMode.Hard) {
for (; c < nextClipInfoCount; c++) {
if (!ApplyAnimation(skeleton, nextClipInfo[c], nextStateInfo, layer, layerWeight, layerBlendMode, useClipWeight1:true))
continue;
++c; break;
}
}
// Mix the rest
for (; c < nextClipInfoCount; c++) {
if (!ApplyAnimation(skeleton, nextClipInfo[c], nextStateInfo, layer, layerWeight, layerBlendMode))
continue;
}
}
c = 0;
if (isInterruptionActive) {
// Apply next clip directly instead of mixing (ie: no crossfade, ignores mecanim transition weights)
if (mode == MixMode.Hard) {
for (; c < interruptingClipInfoCount; c++) {
if (ApplyInterruptionAnimation(skeleton, interpolateWeightTo1,
interruptingClipInfo[c], interruptingStateInfo,
layer, layerWeight, layerBlendMode, interruptingClipTimeAddition, useClipWeight1:true)) {
++c; break;
}
}
}
// Mix the rest
for (; c < interruptingClipInfoCount; c++) {
ApplyInterruptionAnimation(skeleton, interpolateWeightTo1,
interruptingClipInfo[c], interruptingStateInfo,
layer, layerWeight, layerBlendMode, interruptingClipTimeAddition);
}
}
}
}
}
public KeyValuePair<Spine.Animation, float> GetActiveAnimationAndTime (int layer) {
if (layer >= layerClipInfos.Length)
return new KeyValuePair<Spine.Animation, float>(null, 0);
var layerInfos = layerClipInfos[layer];
bool isInterruptionActive = layerInfos.isInterruptionActive;
AnimationClip clip = null;
Spine.Animation animation = null;
AnimatorStateInfo stateInfo;
if (isInterruptionActive && layerInfos.interruptingClipInfoCount > 0) {
clip = layerInfos.interruptingClipInfos[0].clip;
stateInfo = layerInfos.interruptingStateInfo;
}
else {
clip = layerInfos.clipInfos[0].clip;
stateInfo = layerInfos.stateInfo;
}
animation = GetAnimation(clip);
float time = AnimationTime(stateInfo.normalizedTime, clip.length,
clip.isLooping, stateInfo.speed < 0);
return new KeyValuePair<Animation, float>(animation, time);
}
static float AnimationTime (float normalizedTime, float clipLength, bool loop, bool reversed) {
float time = AnimationTime(normalizedTime, clipLength, reversed);
if (loop) return time;
const float EndSnapEpsilon = 1f / 30f; // Workaround for end-duration keys not being applied.
return (clipLength - time < EndSnapEpsilon) ? clipLength : time; // return a time snapped to clipLength;
}
static float AnimationTime (float normalizedTime, float clipLength, bool reversed) {
if (reversed)
normalizedTime = (1 - normalizedTime);
if (normalizedTime < 0.0f)
normalizedTime = (normalizedTime % 1.0f) + 1.0f;
return normalizedTime * clipLength;
}
void InitClipInfosForLayers () {
if (layerClipInfos.Length < animator.layerCount) {
System.Array.Resize<ClipInfos>(ref layerClipInfos, animator.layerCount);
for (int layer = 0, n = animator.layerCount; layer < n; ++layer) {
if (layerClipInfos[layer] == null)
layerClipInfos[layer] = new ClipInfos();
}
}
}
void ClearClipInfosForLayers () {
for (int layer = 0, n = layerClipInfos.Length; layer < n; ++layer) {
if (layerClipInfos[layer] == null)
layerClipInfos[layer] = new ClipInfos();
else {
layerClipInfos[layer].isInterruptionActive = false;
layerClipInfos[layer].isLastFrameOfInterruption = false;
layerClipInfos[layer].clipInfos.Clear();
layerClipInfos[layer].nextClipInfos.Clear();
layerClipInfos[layer].interruptingClipInfos.Clear();
}
}
}
private MixMode GetMixMode (int layer, MixBlend layerBlendMode) {
if (useCustomMixMode) {
MixMode mode = layerMixModes[layer];
// Note: at additive blending it makes no sense to use constant weight 1 at a fadeout anim add1 as
// with override layers, so we use AlwaysMix instead to use the proper weights.
// AlwaysMix leads to the expected result = lower_layer + lerp(add1, add2, transition_weight).
if (layerBlendMode == MixBlend.Add && mode == MixMode.MixNext) {
mode = MixMode.AlwaysMix;
layerMixModes[layer] = mode;
}
return mode;
}
else {
return layerBlendMode == MixBlend.Add ? MixMode.AlwaysMix : MixMode.MixNext;
}
}
#if UNITY_EDITOR
void GetLayerBlendModes() {
if (layerBlendModes.Length < animator.layerCount) {
System.Array.Resize<MixBlend>(ref layerBlendModes, animator.layerCount);
}
for (int layer = 0, n = animator.layerCount; layer < n; ++layer) {
var controller = animator.runtimeAnimatorController as UnityEditor.Animations.AnimatorController;
if (controller != null) {
layerBlendModes[layer] = MixBlend.First;
if (layer > 0) {
layerBlendModes[layer] = controller.layers[layer].blendingMode == UnityEditor.Animations.AnimatorLayerBlendingMode.Additive ?
MixBlend.Add : MixBlend.Replace;
}
}
}
}
#endif
void GetStateUpdatesFromAnimator (int layer) {
var layerInfos = layerClipInfos[layer];
int clipInfoCount = animator.GetCurrentAnimatorClipInfoCount(layer);
int nextClipInfoCount = animator.GetNextAnimatorClipInfoCount(layer);
var clipInfos = layerInfos.clipInfos;
var nextClipInfos = layerInfos.nextClipInfos;
var interruptingClipInfos = layerInfos.interruptingClipInfos;
layerInfos.isInterruptionActive = (clipInfoCount == 0 && clipInfos.Count != 0 &&
nextClipInfoCount == 0 && nextClipInfos.Count != 0);
// Note: during interruption, GetCurrentAnimatorClipInfoCount and GetNextAnimatorClipInfoCount
// are returning 0 in calls above. Therefore we keep previous clipInfos and nextClipInfos
// until the interruption is over.
if (layerInfos.isInterruptionActive) {
// Note: The last frame of a transition interruption
// will have fullPathHash set to 0, therefore we have to use previous
// frame's infos about interruption clips and correct some values
// accordingly (normalizedTime and weight).
var interruptingStateInfo = animator.GetNextAnimatorStateInfo(layer);
layerInfos.isLastFrameOfInterruption = interruptingStateInfo.fullPathHash == 0;
if (!layerInfos.isLastFrameOfInterruption) {
animator.GetNextAnimatorClipInfo(layer, interruptingClipInfos);
layerInfos.interruptingClipInfoCount = interruptingClipInfos.Count;
float oldTime = layerInfos.interruptingStateInfo.normalizedTime;
float newTime = interruptingStateInfo.normalizedTime;
layerInfos.interruptingClipTimeAddition = newTime - oldTime;
layerInfos.interruptingStateInfo = interruptingStateInfo;
}
} else {
layerInfos.clipInfoCount = clipInfoCount;
layerInfos.nextClipInfoCount = nextClipInfoCount;
layerInfos.interruptingClipInfoCount = 0;
layerInfos.isLastFrameOfInterruption = false;
if (clipInfos.Capacity < clipInfoCount) clipInfos.Capacity = clipInfoCount;
if (nextClipInfos.Capacity < nextClipInfoCount) nextClipInfos.Capacity = nextClipInfoCount;
animator.GetCurrentAnimatorClipInfo(layer, clipInfos);
animator.GetNextAnimatorClipInfo(layer, nextClipInfos);
layerInfos.stateInfo = animator.GetCurrentAnimatorStateInfo(layer);
layerInfos.nextStateInfo = animator.GetNextAnimatorStateInfo(layer);
}
}
void GetAnimatorClipInfos (
int layer,
out bool isInterruptionActive,
out int clipInfoCount,
out int nextClipInfoCount,
out int interruptingClipInfoCount,
out IList<AnimatorClipInfo> clipInfo,
out IList<AnimatorClipInfo> nextClipInfo,
out IList<AnimatorClipInfo> interruptingClipInfo,
out bool shallInterpolateWeightTo1) {
var layerInfos = layerClipInfos[layer];
isInterruptionActive = layerInfos.isInterruptionActive;
clipInfoCount = layerInfos.clipInfoCount;
nextClipInfoCount = layerInfos.nextClipInfoCount;
interruptingClipInfoCount = layerInfos.interruptingClipInfoCount;
clipInfo = layerInfos.clipInfos;
nextClipInfo = layerInfos.nextClipInfos;
interruptingClipInfo = isInterruptionActive ? layerInfos.interruptingClipInfos : null;
shallInterpolateWeightTo1 = layerInfos.isLastFrameOfInterruption;
}
void GetAnimatorStateInfos (
int layer,
out bool isInterruptionActive,
out AnimatorStateInfo stateInfo,
out AnimatorStateInfo nextStateInfo,
out AnimatorStateInfo interruptingStateInfo,
out float interruptingClipTimeAddition) {
var layerInfos = layerClipInfos[layer];
isInterruptionActive = layerInfos.isInterruptionActive;
stateInfo = layerInfos.stateInfo;
nextStateInfo = layerInfos.nextStateInfo;
interruptingStateInfo = layerInfos.interruptingStateInfo;
interruptingClipTimeAddition = layerInfos.isLastFrameOfInterruption ? layerInfos.interruptingClipTimeAddition : 0;
}
Spine.Animation GetAnimation (AnimationClip clip) {
int clipNameHashCode;
if (!clipNameHashCodeTable.TryGetValue(clip, out clipNameHashCode)) {
clipNameHashCode = clip.name.GetHashCode();
clipNameHashCodeTable.Add(clip, clipNameHashCode);
}
Spine.Animation animation;
animationTable.TryGetValue(clipNameHashCode, out animation);
return animation;
}
class AnimationClipEqualityComparer : IEqualityComparer<AnimationClip> {
internal static readonly IEqualityComparer<AnimationClip> Instance = new AnimationClipEqualityComparer();
public bool Equals (AnimationClip x, AnimationClip y) { return x.GetInstanceID() == y.GetInstanceID(); }
public int GetHashCode (AnimationClip o) { return o.GetInstanceID(); }
}
class IntEqualityComparer : IEqualityComparer<int> {
internal static readonly IEqualityComparer<int> Instance = new IntEqualityComparer();
public bool Equals (int x, int y) { return x == y; }
public int GetHashCode(int o) { return o; }
}
}
}
}

View File

@@ -1,10 +0,0 @@
fileFormatVersion: 2
guid: f9db98c60740638449864eb028fbe7ad
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 3a361f5ac799a5149b340f9e20da27d1
folderAsset: yes
timeCreated: 1457405502
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,151 +0,0 @@
/******************************************************************************
* 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 {
[RequireComponent(typeof(MeshRenderer), typeof(MeshFilter))]
[HelpURL("http://esotericsoftware.com/spine-unity#SkeletonRenderSeparator")]
public class SkeletonPartsRenderer : MonoBehaviour {
#region Properties
MeshGenerator meshGenerator;
public MeshGenerator MeshGenerator {
get {
LazyIntialize();
return meshGenerator;
}
}
MeshRenderer meshRenderer;
public MeshRenderer MeshRenderer {
get {
LazyIntialize();
return meshRenderer;
}
}
MeshFilter meshFilter;
public MeshFilter MeshFilter {
get {
LazyIntialize();
return meshFilter;
}
}
#endregion
#region Callback Delegates
public delegate void SkeletonPartsRendererDelegate (SkeletonPartsRenderer skeletonPartsRenderer);
/// <summary>OnMeshAndMaterialsUpdated is called at the end of LateUpdate after the Mesh and
/// all materials have been updated.</summary>
public event SkeletonPartsRendererDelegate OnMeshAndMaterialsUpdated;
#endregion
MeshRendererBuffers buffers;
SkeletonRendererInstruction currentInstructions = new SkeletonRendererInstruction();
void LazyIntialize () {
if (buffers == null) {
buffers = new MeshRendererBuffers();
buffers.Initialize();
if (meshGenerator != null) return;
meshGenerator = new MeshGenerator();
meshFilter = GetComponent<MeshFilter>();
meshRenderer = GetComponent<MeshRenderer>();
currentInstructions.Clear();
}
}
public void ClearMesh () {
LazyIntialize();
meshFilter.sharedMesh = null;
}
public void RenderParts (ExposedList<SubmeshInstruction> instructions, int startSubmesh, int endSubmesh) {
LazyIntialize();
// STEP 1: Create instruction
var smartMesh = buffers.GetNextMesh();
currentInstructions.SetWithSubset(instructions, startSubmesh, endSubmesh);
bool updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, smartMesh.instructionUsed);
// STEP 2: Generate mesh buffers.
var currentInstructionsSubmeshesItems = currentInstructions.submeshInstructions.Items;
meshGenerator.Begin();
if (currentInstructions.hasActiveClipping) {
for (int i = 0; i < currentInstructions.submeshInstructions.Count; i++)
meshGenerator.AddSubmesh(currentInstructionsSubmeshesItems[i], updateTriangles);
} else {
meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles);
}
buffers.UpdateSharedMaterials(currentInstructions.submeshInstructions);
// STEP 3: modify mesh.
var mesh = smartMesh.mesh;
if (meshGenerator.VertexCount <= 0) { // Clear an empty mesh
updateTriangles = false;
mesh.Clear();
} else {
meshGenerator.FillVertexData(mesh);
if (updateTriangles) {
meshGenerator.FillTriangles(mesh);
meshRenderer.sharedMaterials = buffers.GetUpdatedSharedMaterialsArray();
} else if (buffers.MaterialsChangedInLastUpdate()) {
meshRenderer.sharedMaterials = buffers.GetUpdatedSharedMaterialsArray();
}
meshGenerator.FillLateVertexData(mesh);
}
meshFilter.sharedMesh = mesh;
smartMesh.instructionUsed.Set(currentInstructions);
if (OnMeshAndMaterialsUpdated != null)
OnMeshAndMaterialsUpdated(this);
}
public void SetPropertyBlock (MaterialPropertyBlock block) {
LazyIntialize();
meshRenderer.SetPropertyBlock(block);
}
public static SkeletonPartsRenderer NewPartsRendererGameObject (Transform parent, string name, int sortingOrder = 0) {
var go = new GameObject(name, typeof(MeshFilter), typeof(MeshRenderer));
go.transform.SetParent(parent, false);
var returnComponent = go.AddComponent<SkeletonPartsRenderer>();
returnComponent.MeshRenderer.sortingOrder = sortingOrder;
return returnComponent;
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 1c0b968d1e7333b499e347acb644f1c1
timeCreated: 1458045480
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,269 +0,0 @@
/******************************************************************************
* 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_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
#define NEW_PREFAB_SYSTEM
#endif
#define SPINE_OPTIONAL_RENDEROVERRIDE
using UnityEngine;
using System.Collections.Generic;
namespace Spine.Unity {
#if NEW_PREFAB_SYSTEM
[ExecuteAlways]
#else
[ExecuteInEditMode]
#endif
[HelpURL("http://esotericsoftware.com/spine-unity#SkeletonRenderSeparator")]
public class SkeletonRenderSeparator : MonoBehaviour {
public const int DefaultSortingOrderIncrement = 5;
#region Inspector
[SerializeField]
protected SkeletonRenderer skeletonRenderer;
public SkeletonRenderer SkeletonRenderer {
get { return skeletonRenderer; }
set {
#if SPINE_OPTIONAL_RENDEROVERRIDE
if (skeletonRenderer != null)
skeletonRenderer.GenerateMeshOverride -= HandleRender;
#endif
skeletonRenderer = value;
if (value == null)
this.enabled = false;
}
}
MeshRenderer mainMeshRenderer;
public bool copyPropertyBlock = true;
[Tooltip("Copies MeshRenderer flags into each parts renderer")]
public bool copyMeshRendererFlags = true;
public List<Spine.Unity.SkeletonPartsRenderer> partsRenderers = new List<SkeletonPartsRenderer>();
#if UNITY_EDITOR
void Reset () {
if (skeletonRenderer == null)
skeletonRenderer = GetComponent<SkeletonRenderer>();
}
#endif
#endregion
#region Callback Delegates
/// <summary>OnMeshAndMaterialsUpdated is called at the end of LateUpdate after the Mesh and
/// all materials have been updated.</summary>
public event SkeletonRenderer.SkeletonRendererDelegate OnMeshAndMaterialsUpdated;
#endregion
#region Runtime Instantiation
/// <summary>Adds a SkeletonRenderSeparator and child SkeletonPartsRenderer GameObjects to a given SkeletonRenderer.</summary>
/// <returns>The to skeleton renderer.</returns>
/// <param name="skeletonRenderer">The target SkeletonRenderer or SkeletonAnimation.</param>
/// <param name="sortingLayerID">Sorting layer to be used for the parts renderers.</param>
/// <param name="extraPartsRenderers">Number of additional SkeletonPartsRenderers on top of the ones determined by counting the number of separator slots.</param>
/// <param name="sortingOrderIncrement">The integer to increment the sorting order per SkeletonPartsRenderer to separate them.</param>
/// <param name="baseSortingOrder">The sorting order value of the first SkeletonPartsRenderer.</param>
/// <param name="addMinimumPartsRenderers">If set to <c>true</c>, a minimum number of SkeletonPartsRenderer GameObjects (determined by separatorSlots.Count + 1) will be added.</param>
public static SkeletonRenderSeparator AddToSkeletonRenderer (SkeletonRenderer skeletonRenderer, int sortingLayerID = 0, int extraPartsRenderers = 0, int sortingOrderIncrement = DefaultSortingOrderIncrement, int baseSortingOrder = 0, bool addMinimumPartsRenderers = true) {
if (skeletonRenderer == null) {
Debug.Log("Tried to add SkeletonRenderSeparator to a null SkeletonRenderer reference.");
return null;
}
var srs = skeletonRenderer.gameObject.AddComponent<SkeletonRenderSeparator>();
srs.skeletonRenderer = skeletonRenderer;
skeletonRenderer.Initialize(false);
int count = extraPartsRenderers;
if (addMinimumPartsRenderers)
count = extraPartsRenderers + skeletonRenderer.separatorSlots.Count + 1;
var skeletonRendererTransform = skeletonRenderer.transform;
var componentRenderers = srs.partsRenderers;
for (int i = 0; i < count; i++) {
var spr = SkeletonPartsRenderer.NewPartsRendererGameObject(skeletonRendererTransform, i.ToString());
var mr = spr.MeshRenderer;
mr.sortingLayerID = sortingLayerID;
mr.sortingOrder = baseSortingOrder + (i * sortingOrderIncrement);
componentRenderers.Add(spr);
}
srs.OnEnable();
#if UNITY_EDITOR
// Make sure editor updates properly in edit mode.
if (!Application.isPlaying) {
skeletonRenderer.enabled = false;
skeletonRenderer.enabled = true;
skeletonRenderer.LateUpdate();
}
#endif
return srs;
}
/// <summary>Add a child SkeletonPartsRenderer GameObject to this SkeletonRenderSeparator.</summary>
public SkeletonPartsRenderer AddPartsRenderer (int sortingOrderIncrement = DefaultSortingOrderIncrement, string name = null) {
int sortingLayerID = 0;
int sortingOrder = 0;
if (partsRenderers.Count > 0) {
var previous = partsRenderers[partsRenderers.Count - 1];
var previousMeshRenderer = previous.MeshRenderer;
sortingLayerID = previousMeshRenderer.sortingLayerID;
sortingOrder = previousMeshRenderer.sortingOrder + sortingOrderIncrement;
}
if (string.IsNullOrEmpty(name))
name = partsRenderers.Count.ToString();
var spr = SkeletonPartsRenderer.NewPartsRendererGameObject(skeletonRenderer.transform, name);
partsRenderers.Add(spr);
var mr = spr.MeshRenderer;
mr.sortingLayerID = sortingLayerID;
mr.sortingOrder = sortingOrder;
return spr;
}
#endregion
public void OnEnable () {
if (skeletonRenderer == null) return;
if (copiedBlock == null) copiedBlock = new MaterialPropertyBlock();
mainMeshRenderer = skeletonRenderer.GetComponent<MeshRenderer>();
#if SPINE_OPTIONAL_RENDEROVERRIDE
skeletonRenderer.GenerateMeshOverride -= HandleRender;
skeletonRenderer.GenerateMeshOverride += HandleRender;
#endif
if (copyMeshRendererFlags) {
var lightProbeUsage = mainMeshRenderer.lightProbeUsage;
bool receiveShadows = mainMeshRenderer.receiveShadows;
var reflectionProbeUsage = mainMeshRenderer.reflectionProbeUsage;
var shadowCastingMode = mainMeshRenderer.shadowCastingMode;
var motionVectorGenerationMode = mainMeshRenderer.motionVectorGenerationMode;
var probeAnchor = mainMeshRenderer.probeAnchor;
for (int i = 0; i < partsRenderers.Count; i++) {
var currentRenderer = partsRenderers[i];
if (currentRenderer == null) continue; // skip null items.
var mr = currentRenderer.MeshRenderer;
mr.lightProbeUsage = lightProbeUsage;
mr.receiveShadows = receiveShadows;
mr.reflectionProbeUsage = reflectionProbeUsage;
mr.shadowCastingMode = shadowCastingMode;
mr.motionVectorGenerationMode = motionVectorGenerationMode;
mr.probeAnchor = probeAnchor;
}
}
}
public void OnDisable () {
if (skeletonRenderer == null) return;
#if SPINE_OPTIONAL_RENDEROVERRIDE
skeletonRenderer.GenerateMeshOverride -= HandleRender;
#endif
skeletonRenderer.LateUpdate();
foreach (var partsRenderer in partsRenderers) {
if (partsRenderer != null)
partsRenderer.ClearMesh();
}
}
MaterialPropertyBlock copiedBlock;
void HandleRender (SkeletonRendererInstruction instruction) {
int rendererCount = partsRenderers.Count;
if (rendererCount <= 0) return;
if (copyPropertyBlock)
mainMeshRenderer.GetPropertyBlock(copiedBlock);
var settings = new MeshGenerator.Settings {
addNormals = skeletonRenderer.addNormals,
calculateTangents = skeletonRenderer.calculateTangents,
immutableTriangles = false, // parts cannot do immutable triangles.
pmaVertexColors = skeletonRenderer.pmaVertexColors,
tintBlack = skeletonRenderer.tintBlack,
useClipping = true,
zSpacing = skeletonRenderer.zSpacing
};
var submeshInstructions = instruction.submeshInstructions;
var submeshInstructionsItems = submeshInstructions.Items;
int lastSubmeshInstruction = submeshInstructions.Count - 1;
int rendererIndex = 0;
var currentRenderer = partsRenderers[rendererIndex];
for (int si = 0, start = 0; si <= lastSubmeshInstruction; si++) {
if (currentRenderer == null)
continue;
if (submeshInstructionsItems[si].forceSeparate || si == lastSubmeshInstruction) {
// Apply properties
var meshGenerator = currentRenderer.MeshGenerator;
meshGenerator.settings = settings;
if (copyPropertyBlock)
currentRenderer.SetPropertyBlock(copiedBlock);
// Render
currentRenderer.RenderParts(instruction.submeshInstructions, start, si + 1);
start = si + 1;
rendererIndex++;
if (rendererIndex < rendererCount) {
currentRenderer = partsRenderers[rendererIndex];
} else {
// Not enough renderers. Skip the rest of the instructions.
break;
}
}
}
if (OnMeshAndMaterialsUpdated != null)
OnMeshAndMaterialsUpdated(this.skeletonRenderer);
// Clear extra renderers if they exist.
for (; rendererIndex < rendererCount; rendererIndex++) {
currentRenderer = partsRenderers[rendererIndex];
if (currentRenderer != null)
partsRenderers[rendererIndex].ClearMesh();
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 5c70a5b35f6ff2541aed8e8346b7e4d5
timeCreated: 1457405791
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,711 +0,0 @@
/******************************************************************************
* 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_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
#define NEW_PREFAB_SYSTEM
#endif
#if UNITY_2018_1_OR_NEWER
#define PER_MATERIAL_PROPERTY_BLOCKS
#endif
#if UNITY_2017_1_OR_NEWER
#define BUILT_IN_SPRITE_MASK_COMPONENT
#endif
#if UNITY_2019_3_OR_NEWER
#define CONFIGURABLE_ENTER_PLAY_MODE
#endif
#define SPINE_OPTIONAL_RENDEROVERRIDE
#define SPINE_OPTIONAL_MATERIALOVERRIDE
using System.Collections.Generic;
using UnityEngine;
namespace Spine.Unity {
/// <summary>Base class of animated Spine skeleton components. This component manages and renders a skeleton.</summary>
#if NEW_PREFAB_SYSTEM
[ExecuteAlways]
#else
[ExecuteInEditMode]
#endif
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer)), DisallowMultipleComponent]
[HelpURL("http://esotericsoftware.com/spine-unity#SkeletonRenderer-Component")]
public class SkeletonRenderer : MonoBehaviour, ISkeletonComponent, IHasSkeletonDataAsset {
public SkeletonDataAsset skeletonDataAsset;
#region Initialization settings
/// <summary>Skin name to use when the Skeleton is initialized.</summary>
[SpineSkin(defaultAsEmptyString:true)] public string initialSkinName;
/// <summary>Enable this parameter when overwriting the Skeleton's skin from an editor script.
/// Otherwise any changes will be overwritten by the next inspector update.</summary>
#if UNITY_EDITOR
public bool EditorSkipSkinSync {
get { return editorSkipSkinSync; }
set { editorSkipSkinSync = value; }
}
protected bool editorSkipSkinSync = false;
#endif
/// <summary>Flip X and Y to use when the Skeleton is initialized.</summary>
public bool initialFlipX, initialFlipY;
#endregion
#region Advanced Render Settings
/// <summary>Update mode to optionally limit updates to e.g. only apply animations but not update the mesh.</summary>
public UpdateMode UpdateMode { get { return updateMode; } set { updateMode = value; } }
protected UpdateMode updateMode = UpdateMode.FullUpdate;
/// <summary>Update mode used when the MeshRenderer becomes invisible
/// (when <c>OnBecameInvisible()</c> is called). Update mode is automatically
/// reset to <c>UpdateMode.FullUpdate</c> when the mesh becomes visible again.</summary>
public UpdateMode updateWhenInvisible = UpdateMode.FullUpdate;
// Submesh Separation
/// <summary>Slot names used to populate separatorSlots list when the Skeleton is initialized. Changing this after initialization does nothing.</summary>
[UnityEngine.Serialization.FormerlySerializedAs("submeshSeparators")][SerializeField][SpineSlot] protected string[] separatorSlotNames = new string[0];
/// <summary>Slots that determine where the render is split. This is used by components such as SkeletonRenderSeparator so that the skeleton can be rendered by two separate renderers on different GameObjects.</summary>
[System.NonSerialized] public readonly List<Slot> separatorSlots = new List<Slot>();
// Render Settings
[Range(-0.1f, 0f)] public float zSpacing;
/// <summary>Use Spine's clipping feature. If false, ClippingAttachments will be ignored.</summary>
public bool useClipping = true;
/// <summary>If true, triangles will not be updated. Enable this as an optimization if the skeleton does not make use of attachment swapping or hiding, or draw order keys. Otherwise, setting this to false may cause errors in rendering.</summary>
public bool immutableTriangles = false;
/// <summary>Multiply vertex color RGB with vertex color alpha. Set this to true if the shader used for rendering is a premultiplied alpha shader. Setting this to false disables single-batch additive slots.</summary>
public bool pmaVertexColors = true;
/// <summary>Clears the state of the render and skeleton when this component or its GameObject is disabled. This prevents previous state from being retained when it is enabled again. When pooling your skeleton, setting this to true can be helpful.</summary>
public bool clearStateOnDisable = false;
/// <summary>If true, second colors on slots will be added to the output Mesh as UV2 and UV3. A special "tint black" shader that interprets UV2 and UV3 as black point colors is required to render this properly.</summary>
public bool tintBlack = false;
/// <summary>If true, the renderer assumes the skeleton only requires one Material and one submesh to render. This allows the MeshGenerator to skip checking for changes in Materials. Enable this as an optimization if the skeleton only uses one Material.</summary>
/// <remarks>This disables SkeletonRenderSeparator functionality.</remarks>
public bool singleSubmesh = false;
#if PER_MATERIAL_PROPERTY_BLOCKS
/// <summary> Applies only when 3+ submeshes are used (2+ materials with alternating order, e.g. "A B A").
/// If true, GPU instancing is disabled at all materials and MaterialPropertyBlocks are assigned at each
/// material to prevent aggressive batching of submeshes by e.g. the LWRP renderer, leading to incorrect
/// draw order (e.g. "A1 B A2" changed to "A1A2 B").
/// You can disable this parameter when everything is drawn correctly to save the additional performance cost.
/// </summary>
public bool fixDrawOrder = false;
#endif
/// <summary>If true, the mesh generator adds normals to the output mesh. For better performance and reduced memory requirements, use a shader that assumes the desired normal.</summary>
[UnityEngine.Serialization.FormerlySerializedAs("calculateNormals")] public bool addNormals = false;
/// <summary>If true, tangents are calculated every frame and added to the Mesh. Enable this when using a shader that uses lighting that requires tangents.</summary>
public bool calculateTangents = false;
#if BUILT_IN_SPRITE_MASK_COMPONENT
/// <summary>This enum controls the mode under which the sprite will interact with the masking system.</summary>
/// <remarks>Interaction modes with <see cref="UnityEngine.SpriteMask"/> components are identical to Unity's <see cref="UnityEngine.SpriteRenderer"/>,
/// see https://docs.unity3d.com/ScriptReference/SpriteMaskInteraction.html. </remarks>
public SpriteMaskInteraction maskInteraction = SpriteMaskInteraction.None;
[System.Serializable]
public class SpriteMaskInteractionMaterials {
public bool AnyMaterialCreated {
get {
return materialsMaskDisabled.Length > 0 ||
materialsInsideMask.Length > 0 ||
materialsOutsideMask.Length > 0;
}
}
/// <summary>Material references for switching material sets at runtime when <see cref="SkeletonRenderer.maskInteraction"/> changes to <see cref="SpriteMaskInteraction.None"/>.</summary>
public Material[] materialsMaskDisabled = new Material[0];
/// <summary>Material references for switching material sets at runtime when <see cref="SkeletonRenderer.maskInteraction"/> changes to <see cref="SpriteMaskInteraction.VisibleInsideMask"/>.</summary>
public Material[] materialsInsideMask = new Material[0];
/// <summary>Material references for switching material sets at runtime when <see cref="SkeletonRenderer.maskInteraction"/> changes to <see cref="SpriteMaskInteraction.VisibleOutsideMask"/>.</summary>
public Material[] materialsOutsideMask = new Material[0];
}
/// <summary>Material references for switching material sets at runtime when <see cref="SkeletonRenderer.maskInteraction"/> changes.</summary>
public SpriteMaskInteractionMaterials maskMaterials = new SpriteMaskInteractionMaterials();
/// <summary>Shader property ID used for the Stencil comparison function.</summary>
public static readonly int STENCIL_COMP_PARAM_ID = Shader.PropertyToID("_StencilComp");
/// <summary>Shader property value used as Stencil comparison function for <see cref="SpriteMaskInteraction.None"/>.</summary>
public const UnityEngine.Rendering.CompareFunction STENCIL_COMP_MASKINTERACTION_NONE = UnityEngine.Rendering.CompareFunction.Always;
/// <summary>Shader property value used as Stencil comparison function for <see cref="SpriteMaskInteraction.VisibleInsideMask"/>.</summary>
public const UnityEngine.Rendering.CompareFunction STENCIL_COMP_MASKINTERACTION_VISIBLE_INSIDE = UnityEngine.Rendering.CompareFunction.LessEqual;
/// <summary>Shader property value used as Stencil comparison function for <see cref="SpriteMaskInteraction.VisibleOutsideMask"/>.</summary>
public const UnityEngine.Rendering.CompareFunction STENCIL_COMP_MASKINTERACTION_VISIBLE_OUTSIDE = UnityEngine.Rendering.CompareFunction.Greater;
#if UNITY_EDITOR
private static bool haveStencilParametersBeenFixed = false;
#endif
#endif // #if BUILT_IN_SPRITE_MASK_COMPONENT
#endregion
#region Overrides
#if SPINE_OPTIONAL_RENDEROVERRIDE
// These are API for anything that wants to take over rendering for a SkeletonRenderer.
public bool disableRenderingOnOverride = true;
public delegate void InstructionDelegate (SkeletonRendererInstruction instruction);
event InstructionDelegate generateMeshOverride;
/// <summary>Allows separate code to take over rendering for this SkeletonRenderer component. The subscriber is passed a SkeletonRendererInstruction argument to determine how to render a skeleton.</summary>
public event InstructionDelegate GenerateMeshOverride {
add {
generateMeshOverride += value;
if (disableRenderingOnOverride && generateMeshOverride != null) {
Initialize(false);
if (meshRenderer)
meshRenderer.enabled = false;
}
}
remove {
generateMeshOverride -= value;
if (disableRenderingOnOverride && generateMeshOverride == null) {
Initialize(false);
if (meshRenderer)
meshRenderer.enabled = true;
}
}
}
/// <summary> Occurs after the vertex data is populated every frame, before the vertices are pushed into the mesh.</summary>
public event Spine.Unity.MeshGeneratorDelegate OnPostProcessVertices;
#endif
#if SPINE_OPTIONAL_MATERIALOVERRIDE
[System.NonSerialized] readonly Dictionary<Material, Material> customMaterialOverride = new Dictionary<Material, Material>();
/// <summary>Use this Dictionary to override a Material with a different Material.</summary>
public Dictionary<Material, Material> CustomMaterialOverride { get { return customMaterialOverride; } }
#endif
[System.NonSerialized] readonly Dictionary<Slot, Material> customSlotMaterials = new Dictionary<Slot, Material>();
/// <summary>Use this Dictionary to use a different Material to render specific Slots.</summary>
public Dictionary<Slot, Material> CustomSlotMaterials { get { return customSlotMaterials; } }
#endregion
#region Mesh Generator
[System.NonSerialized] readonly SkeletonRendererInstruction currentInstructions = new SkeletonRendererInstruction();
readonly MeshGenerator meshGenerator = new MeshGenerator();
[System.NonSerialized] readonly MeshRendererBuffers rendererBuffers = new MeshRendererBuffers();
#endregion
#region Cached component references
MeshRenderer meshRenderer;
MeshFilter meshFilter;
#endregion
#region Skeleton
[System.NonSerialized] public bool valid;
[System.NonSerialized] public Skeleton skeleton;
public Skeleton Skeleton {
get {
Initialize(false);
return skeleton;
}
}
#endregion
public delegate void SkeletonRendererDelegate (SkeletonRenderer skeletonRenderer);
/// <summary>OnRebuild is raised after the Skeleton is successfully initialized.</summary>
public event SkeletonRendererDelegate OnRebuild;
/// <summary>OnMeshAndMaterialsUpdated is called at the end of LateUpdate after the Mesh and
/// all materials have been updated.</summary>
public event SkeletonRendererDelegate OnMeshAndMaterialsUpdated;
public SkeletonDataAsset SkeletonDataAsset { get { return skeletonDataAsset; } } // ISkeletonComponent
#region Runtime Instantiation
public static T NewSpineGameObject<T> (SkeletonDataAsset skeletonDataAsset, bool quiet = false) where T : SkeletonRenderer {
return SkeletonRenderer.AddSpineComponent<T>(new GameObject("New Spine GameObject"), skeletonDataAsset, quiet);
}
/// <summary>Add and prepare a Spine component that derives from SkeletonRenderer to a GameObject at runtime.</summary>
/// <typeparam name="T">T should be SkeletonRenderer or any of its derived classes.</typeparam>
public static T AddSpineComponent<T> (GameObject gameObject, SkeletonDataAsset skeletonDataAsset, bool quiet = false) where T : SkeletonRenderer {
var c = gameObject.AddComponent<T>();
if (skeletonDataAsset != null) {
c.skeletonDataAsset = skeletonDataAsset;
c.Initialize(false, quiet);
}
return c;
}
/// <summary>Applies MeshGenerator settings to the SkeletonRenderer and its internal MeshGenerator.</summary>
public void SetMeshSettings (MeshGenerator.Settings settings) {
this.calculateTangents = settings.calculateTangents;
this.immutableTriangles = settings.immutableTriangles;
this.pmaVertexColors = settings.pmaVertexColors;
this.tintBlack = settings.tintBlack;
this.useClipping = settings.useClipping;
this.zSpacing = settings.zSpacing;
this.meshGenerator.settings = settings;
}
#endregion
public virtual void Awake () {
Initialize(false);
updateMode = updateWhenInvisible;
}
#if UNITY_EDITOR && CONFIGURABLE_ENTER_PLAY_MODE
public virtual void Start () {
Initialize(false);
}
#endif
void OnDisable () {
if (clearStateOnDisable && valid)
ClearState();
}
void OnDestroy () {
rendererBuffers.Dispose();
valid = false;
}
/// <summary>
/// Clears the previously generated mesh and resets the skeleton's pose.</summary>
public virtual void ClearState () {
var meshFilter = GetComponent<MeshFilter>();
if (meshFilter != null) meshFilter.sharedMesh = null;
currentInstructions.Clear();
if (skeleton != null) skeleton.SetToSetupPose();
}
/// <summary>
/// Sets a minimum buffer size for the internal MeshGenerator to prevent excess allocations during animation.
/// </summary>
public void EnsureMeshGeneratorCapacity (int minimumVertexCount) {
meshGenerator.EnsureVertexCapacity(minimumVertexCount);
}
/// <summary>
/// Initialize this component. Attempts to load the SkeletonData and creates the internal Skeleton object and buffers.</summary>
/// <param name="overwrite">If set to <c>true</c>, it will overwrite internal objects if they were already generated. Otherwise, the initialized component will ignore subsequent calls to initialize.</param>
public virtual void Initialize (bool overwrite, bool quiet = false) {
if (valid && !overwrite)
return;
// Clear
{
// Note: do not reset meshFilter.sharedMesh or meshRenderer.sharedMaterial to null,
// otherwise constant reloading will be triggered at prefabs.
currentInstructions.Clear();
rendererBuffers.Clear();
meshGenerator.Begin();
skeleton = null;
valid = false;
}
if (skeletonDataAsset == null)
return;
SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false);
if (skeletonData == null) return;
valid = true;
meshFilter = GetComponent<MeshFilter>();
meshRenderer = GetComponent<MeshRenderer>();
rendererBuffers.Initialize();
skeleton = new Skeleton(skeletonData) {
ScaleX = initialFlipX ? -1 : 1,
ScaleY = initialFlipY ? -1 : 1
};
if (!string.IsNullOrEmpty(initialSkinName) && !string.Equals(initialSkinName, "default", System.StringComparison.Ordinal))
skeleton.SetSkin(initialSkinName);
separatorSlots.Clear();
for (int i = 0; i < separatorSlotNames.Length; i++)
separatorSlots.Add(skeleton.FindSlot(separatorSlotNames[i]));
LateUpdate(); // Generate mesh for the first frame it exists.
if (OnRebuild != null)
OnRebuild(this);
#if UNITY_EDITOR
if (!Application.isPlaying) {
string errorMessage = null;
if (!quiet && MaterialChecks.IsMaterialSetupProblematic(this, ref errorMessage))
Debug.LogWarningFormat(this, "Problematic material setup at {0}: {1}", this.name, errorMessage);
}
#endif
}
/// <summary>
/// Generates a new UnityEngine.Mesh from the internal Skeleton.</summary>
public virtual void LateUpdate () {
if (!valid) return;
#if UNITY_EDITOR && NEW_PREFAB_SYSTEM
// Don't store mesh or material at the prefab, otherwise it will permanently reload
var prefabType = UnityEditor.PrefabUtility.GetPrefabAssetType(this);
if (UnityEditor.PrefabUtility.IsPartOfPrefabAsset(this) &&
(prefabType == UnityEditor.PrefabAssetType.Regular || prefabType == UnityEditor.PrefabAssetType.Variant)) {
return;
}
#endif
if (updateMode != UpdateMode.FullUpdate) return;
#if SPINE_OPTIONAL_RENDEROVERRIDE
bool doMeshOverride = generateMeshOverride != null;
if ((!meshRenderer.enabled) && !doMeshOverride) return;
#else
const bool doMeshOverride = false;
if (!meshRenderer.enabled) return;
#endif
var currentInstructions = this.currentInstructions;
var workingSubmeshInstructions = currentInstructions.submeshInstructions;
var currentSmartMesh = rendererBuffers.GetNextMesh(); // Double-buffer for performance.
bool updateTriangles;
if (this.singleSubmesh) {
// STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. =============================================
MeshGenerator.GenerateSingleSubmeshInstruction(currentInstructions, skeleton, skeletonDataAsset.atlasAssets[0].PrimaryMaterial);
// STEP 1.9. Post-process workingInstructions. ==================================================================================
#if SPINE_OPTIONAL_MATERIALOVERRIDE
if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated
MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride);
#endif
// STEP 2. Update vertex buffer based on verts from the attachments. ===========================================================
meshGenerator.settings = new MeshGenerator.Settings {
pmaVertexColors = this.pmaVertexColors,
zSpacing = this.zSpacing,
useClipping = this.useClipping,
tintBlack = this.tintBlack,
calculateTangents = this.calculateTangents,
addNormals = this.addNormals
};
meshGenerator.Begin();
updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed);
if (currentInstructions.hasActiveClipping) {
meshGenerator.AddSubmesh(workingSubmeshInstructions.Items[0], updateTriangles);
} else {
meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles);
}
} else {
// STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. =============================================
MeshGenerator.GenerateSkeletonRendererInstruction(currentInstructions, skeleton, customSlotMaterials, separatorSlots, doMeshOverride, this.immutableTriangles);
// STEP 1.9. Post-process workingInstructions. ==================================================================================
#if SPINE_OPTIONAL_MATERIALOVERRIDE
if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated
MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride);
#endif
#if SPINE_OPTIONAL_RENDEROVERRIDE
if (doMeshOverride) {
this.generateMeshOverride(currentInstructions);
if (disableRenderingOnOverride) return;
}
#endif
updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed);
// STEP 2. Update vertex buffer based on verts from the attachments. ===========================================================
meshGenerator.settings = new MeshGenerator.Settings {
pmaVertexColors = this.pmaVertexColors,
zSpacing = this.zSpacing,
useClipping = this.useClipping,
tintBlack = this.tintBlack,
calculateTangents = this.calculateTangents,
addNormals = this.addNormals
};
meshGenerator.Begin();
if (currentInstructions.hasActiveClipping)
meshGenerator.BuildMesh(currentInstructions, updateTriangles);
else
meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles);
}
if (OnPostProcessVertices != null) OnPostProcessVertices.Invoke(this.meshGenerator.Buffers);
// STEP 3. Move the mesh data into a UnityEngine.Mesh ===========================================================================
var currentMesh = currentSmartMesh.mesh;
meshGenerator.FillVertexData(currentMesh);
rendererBuffers.UpdateSharedMaterials(workingSubmeshInstructions);
bool materialsChanged = rendererBuffers.MaterialsChangedInLastUpdate();
if (updateTriangles) { // Check if the triangles should also be updated.
meshGenerator.FillTriangles(currentMesh);
meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray();
} else if (materialsChanged) {
meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray();
}
if (materialsChanged && (this.maskMaterials.AnyMaterialCreated)) {
this.maskMaterials = new SpriteMaskInteractionMaterials();
}
meshGenerator.FillLateVertexData(currentMesh);
// STEP 4. The UnityEngine.Mesh is ready. Set it as the MeshFilter's mesh. Store the instructions used for that mesh. ===========
meshFilter.sharedMesh = currentMesh;
currentSmartMesh.instructionUsed.Set(currentInstructions);
#if BUILT_IN_SPRITE_MASK_COMPONENT
if (meshRenderer != null) {
AssignSpriteMaskMaterials();
}
#endif
#if PER_MATERIAL_PROPERTY_BLOCKS
if (fixDrawOrder && meshRenderer.sharedMaterials.Length > 2) {
SetMaterialSettingsToFixDrawOrder();
}
#endif
if (OnMeshAndMaterialsUpdated != null)
OnMeshAndMaterialsUpdated(this);
}
public void OnBecameVisible () {
UpdateMode previousUpdateMode = updateMode;
updateMode = UpdateMode.FullUpdate;
if (previousUpdateMode != UpdateMode.FullUpdate)
LateUpdate(); // OnBecameVisible is called after LateUpdate()
}
public void OnBecameInvisible () {
updateMode = updateWhenInvisible;
}
public void FindAndApplySeparatorSlots (string startsWith, bool clearExistingSeparators = true, bool updateStringArray = false) {
if (string.IsNullOrEmpty(startsWith)) return;
FindAndApplySeparatorSlots(
(slotName) => slotName.StartsWith(startsWith),
clearExistingSeparators,
updateStringArray
);
}
public void FindAndApplySeparatorSlots (System.Func<string, bool> slotNamePredicate, bool clearExistingSeparators = true, bool updateStringArray = false) {
if (slotNamePredicate == null) return;
if (!valid) return;
if (clearExistingSeparators)
separatorSlots.Clear();
var slots = skeleton.slots;
foreach (var slot in slots) {
if (slotNamePredicate.Invoke(slot.data.name))
separatorSlots.Add(slot);
}
if (updateStringArray) {
var detectedSeparatorNames = new List<string>();
foreach (var slot in skeleton.slots) {
string slotName = slot.data.name;
if (slotNamePredicate.Invoke(slotName))
detectedSeparatorNames.Add(slotName);
}
if (!clearExistingSeparators) {
string[] originalNames = this.separatorSlotNames;
foreach (string originalName in originalNames)
detectedSeparatorNames.Add(originalName);
}
this.separatorSlotNames = detectedSeparatorNames.ToArray();
}
}
public void ReapplySeparatorSlotNames () {
if (!valid)
return;
separatorSlots.Clear();
for (int i = 0, n = separatorSlotNames.Length; i < n; i++) {
var slot = skeleton.FindSlot(separatorSlotNames[i]);
if (slot != null) {
separatorSlots.Add(slot);
}
#if UNITY_EDITOR
else if (!string.IsNullOrEmpty(separatorSlotNames[i]))
{
Debug.LogWarning(separatorSlotNames[i] + " is not a slot in " + skeletonDataAsset.skeletonJSON.name);
}
#endif
}
}
#if BUILT_IN_SPRITE_MASK_COMPONENT
private void AssignSpriteMaskMaterials()
{
#if UNITY_EDITOR
if (!Application.isPlaying && !UnityEditor.EditorApplication.isUpdating) {
EditorFixStencilCompParameters();
}
#endif
if (Application.isPlaying) {
if (maskInteraction != SpriteMaskInteraction.None && maskMaterials.materialsMaskDisabled.Length == 0)
maskMaterials.materialsMaskDisabled = meshRenderer.sharedMaterials;
}
if (maskMaterials.materialsMaskDisabled.Length > 0 && maskMaterials.materialsMaskDisabled[0] != null &&
maskInteraction == SpriteMaskInteraction.None) {
this.meshRenderer.materials = maskMaterials.materialsMaskDisabled;
}
else if (maskInteraction == SpriteMaskInteraction.VisibleInsideMask) {
if (maskMaterials.materialsInsideMask.Length == 0 || maskMaterials.materialsInsideMask[0] == null) {
if (!InitSpriteMaskMaterialsInsideMask())
return;
}
this.meshRenderer.materials = maskMaterials.materialsInsideMask;
}
else if (maskInteraction == SpriteMaskInteraction.VisibleOutsideMask) {
if (maskMaterials.materialsOutsideMask.Length == 0 || maskMaterials.materialsOutsideMask[0] == null) {
if (!InitSpriteMaskMaterialsOutsideMask())
return;
}
this.meshRenderer.materials = maskMaterials.materialsOutsideMask;
}
}
private bool InitSpriteMaskMaterialsInsideMask()
{
return InitSpriteMaskMaterialsForMaskType(STENCIL_COMP_MASKINTERACTION_VISIBLE_INSIDE, ref maskMaterials.materialsInsideMask);
}
private bool InitSpriteMaskMaterialsOutsideMask()
{
return InitSpriteMaskMaterialsForMaskType(STENCIL_COMP_MASKINTERACTION_VISIBLE_OUTSIDE, ref maskMaterials.materialsOutsideMask);
}
private bool InitSpriteMaskMaterialsForMaskType(UnityEngine.Rendering.CompareFunction maskFunction, ref Material[] materialsToFill)
{
#if UNITY_EDITOR
if (!Application.isPlaying) {
return false;
}
#endif
var originalMaterials = maskMaterials.materialsMaskDisabled;
materialsToFill = new Material[originalMaterials.Length];
for (int i = 0; i < originalMaterials.Length; i++) {
Material newMaterial = new Material(originalMaterials[i]);
newMaterial.SetFloat(STENCIL_COMP_PARAM_ID, (int)maskFunction);
materialsToFill[i] = newMaterial;
}
return true;
}
#if UNITY_EDITOR
private void EditorFixStencilCompParameters() {
if (!haveStencilParametersBeenFixed && HasAnyStencilComp0Material()) {
haveStencilParametersBeenFixed = true;
FixAllProjectMaterialsStencilCompParameters();
}
}
private void FixAllProjectMaterialsStencilCompParameters() {
string[] materialGUIDS = UnityEditor.AssetDatabase.FindAssets("t:material");
foreach (var guid in materialGUIDS) {
string path = UnityEditor.AssetDatabase.GUIDToAssetPath(guid);
if (!string.IsNullOrEmpty(path)) {
var mat = UnityEditor.AssetDatabase.LoadAssetAtPath<Material>(path);
if (mat.HasProperty(STENCIL_COMP_PARAM_ID) && mat.GetFloat(STENCIL_COMP_PARAM_ID) == 0) {
mat.SetFloat(STENCIL_COMP_PARAM_ID, (int)STENCIL_COMP_MASKINTERACTION_NONE);
}
}
}
UnityEditor.AssetDatabase.Refresh();
UnityEditor.AssetDatabase.SaveAssets();
}
private bool HasAnyStencilComp0Material() {
if (meshRenderer == null)
return false;
foreach (var mat in meshRenderer.sharedMaterials) {
if (mat != null && mat.HasProperty(STENCIL_COMP_PARAM_ID)) {
float currentCompValue = mat.GetFloat(STENCIL_COMP_PARAM_ID);
if (currentCompValue == 0)
return true;
}
}
return false;
}
#endif // UNITY_EDITOR
#endif //#if BUILT_IN_SPRITE_MASK_COMPONENT
#if PER_MATERIAL_PROPERTY_BLOCKS
private MaterialPropertyBlock reusedPropertyBlock;
public static readonly int SUBMESH_DUMMY_PARAM_ID = Shader.PropertyToID("_Submesh");
/// <summary>
/// This method was introduced as a workaround for too aggressive submesh draw call batching,
/// leading to incorrect draw order when 3+ materials are used at submeshes in alternating order.
/// Otherwise, e.g. when using Lightweight Render Pipeline, deliberately separated draw calls
/// "A1 B A2" are reordered to "A1A2 B", regardless of batching-related project settings.
/// </summary>
private void SetMaterialSettingsToFixDrawOrder() {
if (reusedPropertyBlock == null) reusedPropertyBlock = new MaterialPropertyBlock();
bool hasPerRendererBlock = meshRenderer.HasPropertyBlock();
if (hasPerRendererBlock) {
meshRenderer.GetPropertyBlock(reusedPropertyBlock);
}
for (int i = 0; i < meshRenderer.sharedMaterials.Length; ++i) {
if (!meshRenderer.sharedMaterials[i])
continue;
if (!hasPerRendererBlock) meshRenderer.GetPropertyBlock(reusedPropertyBlock, i);
// Note: this parameter shall not exist at any shader, then Unity will create separate
// material instances (not in terms of memory cost or leakage).
reusedPropertyBlock.SetFloat(SUBMESH_DUMMY_PARAM_ID, i);
meshRenderer.SetPropertyBlock(reusedPropertyBlock, i);
meshRenderer.sharedMaterials[i].enableInstancing = false;
}
}
#endif
}
}

View File

@@ -1,10 +0,0 @@
fileFormatVersion: 2
guid: e075b9a3e08e2f74fbd651c858ab16ed
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: a7236dbdc6a4e5a4989483dac97aee0b
folderAsset: yes
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,211 +0,0 @@
/******************************************************************************
* 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_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
#define NEW_PREFAB_SYSTEM
#endif
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Spine.Unity {
#if NEW_PREFAB_SYSTEM
[ExecuteAlways]
#else
[ExecuteInEditMode]
#endif
[HelpURL("http://esotericsoftware.com/spine-unity#SkeletonGraphicCustomMaterials")]
public class SkeletonGraphicCustomMaterials : MonoBehaviour {
#region Inspector
public SkeletonGraphic skeletonGraphic;
[SerializeField] protected List<AtlasMaterialOverride> customMaterialOverrides = new List<AtlasMaterialOverride>();
[SerializeField] protected List<AtlasTextureOverride> customTextureOverrides = new List<AtlasTextureOverride>();
#if UNITY_EDITOR
void Reset () {
skeletonGraphic = GetComponent<SkeletonGraphic>();
// Populate material list
if (skeletonGraphic != null && skeletonGraphic.skeletonDataAsset != null) {
var atlasAssets = skeletonGraphic.skeletonDataAsset.atlasAssets;
var initialAtlasMaterialOverrides = new List<AtlasMaterialOverride>();
foreach (AtlasAssetBase atlasAsset in atlasAssets) {
foreach (Material atlasMaterial in atlasAsset.Materials) {
var atlasMaterialOverride = new AtlasMaterialOverride {
overrideEnabled = false,
originalTexture = atlasMaterial.mainTexture
};
initialAtlasMaterialOverrides.Add(atlasMaterialOverride);
}
}
customMaterialOverrides = initialAtlasMaterialOverrides;
}
// Populate texture list
if (skeletonGraphic != null && skeletonGraphic.skeletonDataAsset != null) {
var atlasAssets = skeletonGraphic.skeletonDataAsset.atlasAssets;
var initialAtlasTextureOverrides = new List<AtlasTextureOverride>();
foreach (AtlasAssetBase atlasAsset in atlasAssets) {
foreach (Material atlasMaterial in atlasAsset.Materials) {
var atlasTextureOverride = new AtlasTextureOverride {
overrideEnabled = false,
originalTexture = atlasMaterial.mainTexture
};
initialAtlasTextureOverrides.Add(atlasTextureOverride);
}
}
customTextureOverrides = initialAtlasTextureOverrides;
}
}
#endif
#endregion
void SetCustomMaterialOverrides () {
if (skeletonGraphic == null) {
Debug.LogError("skeletonGraphic == null");
return;
}
for (int i = 0; i < customMaterialOverrides.Count; i++) {
AtlasMaterialOverride atlasMaterialOverride = customMaterialOverrides[i];
if (atlasMaterialOverride.overrideEnabled)
skeletonGraphic.CustomMaterialOverride[atlasMaterialOverride.originalTexture] = atlasMaterialOverride.replacementMaterial;
}
}
void RemoveCustomMaterialOverrides () {
if (skeletonGraphic == null) {
Debug.LogError("skeletonGraphic == null");
return;
}
for (int i = 0; i < customMaterialOverrides.Count; i++) {
AtlasMaterialOverride atlasMaterialOverride = customMaterialOverrides[i];
Material currentMaterial;
if (!skeletonGraphic.CustomMaterialOverride.TryGetValue(atlasMaterialOverride.originalTexture, out currentMaterial))
continue;
// Do not revert the material if it was changed by something else
if (currentMaterial != atlasMaterialOverride.replacementMaterial)
continue;
skeletonGraphic.CustomMaterialOverride.Remove(atlasMaterialOverride.originalTexture);
}
}
void SetCustomTextureOverrides () {
if (skeletonGraphic == null) {
Debug.LogError("skeletonGraphic == null");
return;
}
for (int i = 0; i < customTextureOverrides.Count; i++) {
AtlasTextureOverride atlasTextureOverride = customTextureOverrides[i];
if (atlasTextureOverride.overrideEnabled)
skeletonGraphic.CustomTextureOverride[atlasTextureOverride.originalTexture] = atlasTextureOverride.replacementTexture;
}
}
void RemoveCustomTextureOverrides () {
if (skeletonGraphic == null) {
Debug.LogError("skeletonGraphic == null");
return;
}
for (int i = 0; i < customTextureOverrides.Count; i++) {
AtlasTextureOverride atlasTextureOverride = customTextureOverrides[i];
Texture currentTexture;
if (!skeletonGraphic.CustomTextureOverride.TryGetValue(atlasTextureOverride.originalTexture, out currentTexture))
continue;
// Do not revert the material if it was changed by something else
if (currentTexture != atlasTextureOverride.replacementTexture)
continue;
skeletonGraphic.CustomTextureOverride.Remove(atlasTextureOverride.originalTexture);
}
}
// OnEnable applies the overrides at runtime, and when the editor loads.
void OnEnable () {
if (skeletonGraphic == null)
skeletonGraphic = GetComponent<SkeletonGraphic>();
if (skeletonGraphic == null) {
Debug.LogError("skeletonGraphic == null");
return;
}
skeletonGraphic.Initialize(false);
SetCustomMaterialOverrides();
SetCustomTextureOverrides();
}
// OnDisable removes the overrides at runtime, and in the editor when the component is disabled or destroyed.
void OnDisable () {
if (skeletonGraphic == null) {
Debug.LogError("skeletonGraphic == null");
return;
}
RemoveCustomMaterialOverrides();
RemoveCustomTextureOverrides();
}
[Serializable]
public struct AtlasMaterialOverride : IEquatable<AtlasMaterialOverride> {
public bool overrideEnabled;
public Texture originalTexture;
public Material replacementMaterial;
public bool Equals (AtlasMaterialOverride other) {
return overrideEnabled == other.overrideEnabled && originalTexture == other.originalTexture && replacementMaterial == other.replacementMaterial;
}
}
[Serializable]
public struct AtlasTextureOverride : IEquatable<AtlasTextureOverride> {
public bool overrideEnabled;
public Texture originalTexture;
public Texture replacementTexture;
public bool Equals (AtlasTextureOverride other) {
return overrideEnabled == other.overrideEnabled && originalTexture == other.originalTexture && replacementTexture == other.replacementTexture;
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 6c8717e10b272bf42b05d363ac2679a6
timeCreated: 1588789074
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,212 +0,0 @@
/******************************************************************************
* 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_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
#define NEW_PREFAB_SYSTEM
#endif
#define SPINE_OPTIONAL_MATERIALOVERRIDE
// Contributed by: Lost Polygon
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Spine.Unity {
#if NEW_PREFAB_SYSTEM
[ExecuteAlways]
#else
[ExecuteInEditMode]
#endif
[HelpURL("http://esotericsoftware.com/spine-unity#SkeletonRendererCustomMaterials")]
public class SkeletonRendererCustomMaterials : MonoBehaviour {
#region Inspector
public SkeletonRenderer skeletonRenderer;
[SerializeField] protected List<SlotMaterialOverride> customSlotMaterials = new List<SlotMaterialOverride>();
[SerializeField] protected List<AtlasMaterialOverride> customMaterialOverrides = new List<AtlasMaterialOverride>();
#if UNITY_EDITOR
void Reset () {
skeletonRenderer = GetComponent<SkeletonRenderer>();
// Populate atlas list
if (skeletonRenderer != null && skeletonRenderer.skeletonDataAsset != null) {
var atlasAssets = skeletonRenderer.skeletonDataAsset.atlasAssets;
var initialAtlasMaterialOverrides = new List<AtlasMaterialOverride>();
foreach (AtlasAssetBase atlasAsset in atlasAssets) {
foreach (Material atlasMaterial in atlasAsset.Materials) {
var atlasMaterialOverride = new AtlasMaterialOverride {
overrideDisabled = true,
originalMaterial = atlasMaterial
};
initialAtlasMaterialOverrides.Add(atlasMaterialOverride);
}
}
customMaterialOverrides = initialAtlasMaterialOverrides;
}
}
#endif
#endregion
void SetCustomSlotMaterials () {
if (skeletonRenderer == null) {
Debug.LogError("skeletonRenderer == null");
return;
}
for (int i = 0; i < customSlotMaterials.Count; i++) {
SlotMaterialOverride slotMaterialOverride = customSlotMaterials[i];
if (slotMaterialOverride.overrideDisabled || string.IsNullOrEmpty(slotMaterialOverride.slotName))
continue;
Slot slotObject = skeletonRenderer.skeleton.FindSlot(slotMaterialOverride.slotName);
skeletonRenderer.CustomSlotMaterials[slotObject] = slotMaterialOverride.material;
}
}
void RemoveCustomSlotMaterials () {
if (skeletonRenderer == null) {
Debug.LogError("skeletonRenderer == null");
return;
}
for (int i = 0; i < customSlotMaterials.Count; i++) {
SlotMaterialOverride slotMaterialOverride = customSlotMaterials[i];
if (string.IsNullOrEmpty(slotMaterialOverride.slotName))
continue;
Slot slotObject = skeletonRenderer.skeleton.FindSlot(slotMaterialOverride.slotName);
Material currentMaterial;
if (!skeletonRenderer.CustomSlotMaterials.TryGetValue(slotObject, out currentMaterial))
continue;
// Do not revert the material if it was changed by something else
if (currentMaterial != slotMaterialOverride.material)
continue;
skeletonRenderer.CustomSlotMaterials.Remove(slotObject);
}
}
void SetCustomMaterialOverrides () {
if (skeletonRenderer == null) {
Debug.LogError("skeletonRenderer == null");
return;
}
#if SPINE_OPTIONAL_MATERIALOVERRIDE
for (int i = 0; i < customMaterialOverrides.Count; i++) {
AtlasMaterialOverride atlasMaterialOverride = customMaterialOverrides[i];
if (atlasMaterialOverride.overrideDisabled)
continue;
skeletonRenderer.CustomMaterialOverride[atlasMaterialOverride.originalMaterial] = atlasMaterialOverride.replacementMaterial;
}
#endif
}
void RemoveCustomMaterialOverrides () {
if (skeletonRenderer == null) {
Debug.LogError("skeletonRenderer == null");
return;
}
#if SPINE_OPTIONAL_MATERIALOVERRIDE
for (int i = 0; i < customMaterialOverrides.Count; i++) {
AtlasMaterialOverride atlasMaterialOverride = customMaterialOverrides[i];
Material currentMaterial;
if (!skeletonRenderer.CustomMaterialOverride.TryGetValue(atlasMaterialOverride.originalMaterial, out currentMaterial))
continue;
// Do not revert the material if it was changed by something else
if (currentMaterial != atlasMaterialOverride.replacementMaterial)
continue;
skeletonRenderer.CustomMaterialOverride.Remove(atlasMaterialOverride.originalMaterial);
}
#endif
}
// OnEnable applies the overrides at runtime, and when the editor loads.
void OnEnable () {
if (skeletonRenderer == null)
skeletonRenderer = GetComponent<SkeletonRenderer>();
if (skeletonRenderer == null) {
Debug.LogError("skeletonRenderer == null");
return;
}
skeletonRenderer.Initialize(false);
SetCustomMaterialOverrides();
SetCustomSlotMaterials();
}
// OnDisable removes the overrides at runtime, and in the editor when the component is disabled or destroyed.
void OnDisable () {
if (skeletonRenderer == null) {
Debug.LogError("skeletonRenderer == null");
return;
}
RemoveCustomMaterialOverrides();
RemoveCustomSlotMaterials();
}
[Serializable]
public struct SlotMaterialOverride : IEquatable<SlotMaterialOverride> {
public bool overrideDisabled;
[SpineSlot]
public string slotName;
public Material material;
public bool Equals (SlotMaterialOverride other) {
return overrideDisabled == other.overrideDisabled && slotName == other.slotName && material == other.material;
}
}
[Serializable]
public struct AtlasMaterialOverride : IEquatable<AtlasMaterialOverride> {
public bool overrideDisabled;
public Material originalMaterial;
public Material replacementMaterial;
public bool Equals (AtlasMaterialOverride other) {
return overrideDisabled == other.overrideDisabled && originalMaterial == other.originalMaterial && replacementMaterial == other.replacementMaterial;
}
}
}
}

View File

@@ -1,10 +0,0 @@
fileFormatVersion: 2
guid: 26947ae098a8447408d80c0c86e35b48
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,5 +0,0 @@
fileFormatVersion: 2
guid: f6e0caaafe294de48af468a6a9321473
folderAsset: yes
DefaultImporter:
userData:

View File

@@ -1,469 +0,0 @@
/******************************************************************************
* 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_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
#define NEW_PREFAB_SYSTEM
#endif
using UnityEngine;
using System.Collections.Generic;
namespace Spine.Unity {
#if NEW_PREFAB_SYSTEM
[ExecuteAlways]
#else
[ExecuteInEditMode]
#endif
[RequireComponent(typeof(ISkeletonAnimation))]
[HelpURL("http://esotericsoftware.com/spine-unity#SkeletonUtility")]
public sealed class SkeletonUtility : MonoBehaviour {
#region BoundingBoxAttachment
public static PolygonCollider2D AddBoundingBoxGameObject (Skeleton skeleton, string skinName, string slotName, string attachmentName, Transform parent, bool isTrigger = true) {
Skin skin = string.IsNullOrEmpty(skinName) ? skeleton.data.defaultSkin : skeleton.data.FindSkin(skinName);
if (skin == null) {
Debug.LogError("Skin " + skinName + " not found!");
return null;
}
var attachment = skin.GetAttachment(skeleton.FindSlotIndex(slotName), attachmentName);
if (attachment == null) {
Debug.LogFormat("Attachment in slot '{0}' named '{1}' not found in skin '{2}'.", slotName, attachmentName, skin.name);
return null;
}
var box = attachment as BoundingBoxAttachment;
if (box != null) {
var slot = skeleton.FindSlot(slotName);
return AddBoundingBoxGameObject(box.Name, box, slot, parent, isTrigger);
} else {
Debug.LogFormat("Attachment '{0}' was not a Bounding Box.", attachmentName);
return null;
}
}
public static PolygonCollider2D AddBoundingBoxGameObject (string name, BoundingBoxAttachment box, Slot slot, Transform parent, bool isTrigger = true) {
var go = new GameObject("[BoundingBox]" + (string.IsNullOrEmpty(name) ? box.Name : name));
#if UNITY_EDITOR
if (!Application.isPlaying)
UnityEditor.Undo.RegisterCreatedObjectUndo(go, "Spawn BoundingBox");
# endif
var got = go.transform;
got.parent = parent;
got.localPosition = Vector3.zero;
got.localRotation = Quaternion.identity;
got.localScale = Vector3.one;
return AddBoundingBoxAsComponent(box, slot, go, isTrigger);
}
public static PolygonCollider2D AddBoundingBoxAsComponent (BoundingBoxAttachment box, Slot slot, GameObject gameObject, bool isTrigger = true) {
if (box == null) return null;
var collider = gameObject.AddComponent<PolygonCollider2D>();
collider.isTrigger = isTrigger;
SetColliderPointsLocal(collider, slot, box);
return collider;
}
public static void SetColliderPointsLocal (PolygonCollider2D collider, Slot slot, BoundingBoxAttachment box, float scale = 1.0f) {
if (box == null) return;
if (box.IsWeighted()) Debug.LogWarning("UnityEngine.PolygonCollider2D does not support weighted or animated points. Collider points will not be animated and may have incorrect orientation. If you want to use it as a collider, please remove weights and animations from the bounding box in Spine editor.");
var verts = box.GetLocalVertices(slot, null);
if (scale != 1.0f) {
for (int i = 0, n = verts.Length; i < n; ++i)
verts[i] *= scale;
}
collider.SetPath(0, verts);
}
public static Bounds GetBoundingBoxBounds (BoundingBoxAttachment boundingBox, float depth = 0) {
float[] floats = boundingBox.Vertices;
int floatCount = floats.Length;
Bounds bounds = new Bounds();
bounds.center = new Vector3(floats[0], floats[1], 0);
for (int i = 2; i < floatCount; i += 2)
bounds.Encapsulate(new Vector3(floats[i], floats[i + 1], 0));
Vector3 size = bounds.size;
size.z = depth;
bounds.size = size;
return bounds;
}
public static Rigidbody2D AddBoneRigidbody2D (GameObject gameObject, bool isKinematic = true, float gravityScale = 0f) {
var rb = gameObject.GetComponent<Rigidbody2D>();
if (rb == null) {
rb = gameObject.AddComponent<Rigidbody2D>();
rb.isKinematic = isKinematic;
rb.gravityScale = gravityScale;
}
return rb;
}
#endregion
public delegate void SkeletonUtilityDelegate ();
public event SkeletonUtilityDelegate OnReset;
public Transform boneRoot;
/// <summary>
/// If true, <see cref="Skeleton.ScaleX"/> and <see cref="Skeleton.ScaleY"/> are followed
/// by 180 degree rotation. If false, negative Transform scale is used.
/// Note that using negative scale is consistent with previous behaviour (hence the default),
/// however causes serious problems with rigidbodies and physics. Therefore, it is recommended to
/// enable this parameter where possible. When creating hinge chains for a chain of skeleton bones
/// via <see cref="SkeletonUtilityBone"/>, it is mandatory to have <c>flipBy180DegreeRotation</c> enabled.
/// </summary>
public bool flipBy180DegreeRotation = false;
void Update () {
var skeleton = skeletonComponent.Skeleton;
if (skeleton != null && boneRoot != null) {
if (flipBy180DegreeRotation) {
boneRoot.localScale = new Vector3(Mathf.Abs(skeleton.ScaleX), Mathf.Abs(skeleton.ScaleY), 1f);
boneRoot.eulerAngles = new Vector3(skeleton.ScaleY > 0 ? 0 : 180,
skeleton.ScaleX > 0 ? 0 : 180,
0);
}
else {
boneRoot.localScale = new Vector3(skeleton.ScaleX, skeleton.ScaleY, 1f);
}
}
if (canvas != null) {
positionScale = canvas.referencePixelsPerUnit;
}
}
[HideInInspector] public SkeletonRenderer skeletonRenderer;
[HideInInspector] public SkeletonGraphic skeletonGraphic;
private Canvas canvas;
[System.NonSerialized] public ISkeletonAnimation skeletonAnimation;
private ISkeletonComponent skeletonComponent;
[System.NonSerialized] public List<SkeletonUtilityBone> boneComponents = new List<SkeletonUtilityBone>();
[System.NonSerialized] public List<SkeletonUtilityConstraint> constraintComponents = new List<SkeletonUtilityConstraint>();
public ISkeletonComponent SkeletonComponent {
get {
if (skeletonComponent == null) {
skeletonComponent = skeletonRenderer != null ? skeletonRenderer.GetComponent<ISkeletonComponent>() :
skeletonGraphic != null ? skeletonGraphic.GetComponent<ISkeletonComponent>() :
GetComponent<ISkeletonComponent>();
}
return skeletonComponent;
}
}
public Skeleton Skeleton {
get {
if (SkeletonComponent == null)
return null;
return skeletonComponent.Skeleton;
}
}
public bool IsValid {
get {
return (skeletonRenderer != null && skeletonRenderer.valid) ||
(skeletonGraphic != null && skeletonGraphic.IsValid);
}
}
public float PositionScale { get { return positionScale; } }
float positionScale = 1.0f;
bool hasOverrideBones;
bool hasConstraints;
bool needToReprocessBones;
public void ResubscribeEvents () {
OnDisable();
OnEnable();
}
void OnEnable () {
if (skeletonRenderer == null) {
skeletonRenderer = GetComponent<SkeletonRenderer>();
}
if (skeletonGraphic == null) {
skeletonGraphic = GetComponent<SkeletonGraphic>();
}
if (skeletonAnimation == null) {
skeletonAnimation = skeletonRenderer != null ? skeletonRenderer.GetComponent<ISkeletonAnimation>() :
skeletonGraphic != null ? skeletonGraphic.GetComponent<ISkeletonAnimation>() :
GetComponent<ISkeletonAnimation>();
}
if (skeletonComponent == null) {
skeletonComponent = skeletonRenderer != null ? skeletonRenderer.GetComponent<ISkeletonComponent>() :
skeletonGraphic != null ? skeletonGraphic.GetComponent<ISkeletonComponent>() :
GetComponent<ISkeletonComponent>();
}
if (skeletonRenderer != null) {
skeletonRenderer.OnRebuild -= HandleRendererReset;
skeletonRenderer.OnRebuild += HandleRendererReset;
}
else if (skeletonGraphic != null) {
skeletonGraphic.OnRebuild -= HandleRendererReset;
skeletonGraphic.OnRebuild += HandleRendererReset;
canvas = skeletonGraphic.canvas;
if (canvas == null)
canvas = skeletonGraphic.GetComponentInParent<Canvas>();
if (canvas == null)
positionScale = 100.0f;
}
if (skeletonAnimation != null) {
skeletonAnimation.UpdateLocal -= UpdateLocal;
skeletonAnimation.UpdateLocal += UpdateLocal;
}
CollectBones();
}
void Start () {
//recollect because order of operations failure when switching between game mode and edit mode...
CollectBones();
}
void OnDisable () {
if (skeletonRenderer != null)
skeletonRenderer.OnRebuild -= HandleRendererReset;
if (skeletonGraphic != null)
skeletonGraphic.OnRebuild -= HandleRendererReset;
if (skeletonAnimation != null) {
skeletonAnimation.UpdateLocal -= UpdateLocal;
skeletonAnimation.UpdateWorld -= UpdateWorld;
skeletonAnimation.UpdateComplete -= UpdateComplete;
}
}
void HandleRendererReset (SkeletonRenderer r) {
if (OnReset != null) OnReset();
CollectBones();
}
void HandleRendererReset (SkeletonGraphic g) {
if (OnReset != null) OnReset();
CollectBones();
}
public void RegisterBone (SkeletonUtilityBone bone) {
if (boneComponents.Contains(bone)) {
return;
} else {
boneComponents.Add(bone);
needToReprocessBones = true;
}
}
public void UnregisterBone (SkeletonUtilityBone bone) {
boneComponents.Remove(bone);
}
public void RegisterConstraint (SkeletonUtilityConstraint constraint) {
if (constraintComponents.Contains(constraint))
return;
else {
constraintComponents.Add(constraint);
needToReprocessBones = true;
}
}
public void UnregisterConstraint (SkeletonUtilityConstraint constraint) {
constraintComponents.Remove(constraint);
}
public void CollectBones () {
var skeleton = skeletonComponent.Skeleton;
if (skeleton == null) return;
if (boneRoot != null) {
var constraintTargets = new List<System.Object>();
var ikConstraints = skeleton.IkConstraints;
for (int i = 0, n = ikConstraints.Count; i < n; i++)
constraintTargets.Add(ikConstraints.Items[i].target);
var transformConstraints = skeleton.TransformConstraints;
for (int i = 0, n = transformConstraints.Count; i < n; i++)
constraintTargets.Add(transformConstraints.Items[i].target);
var boneComponents = this.boneComponents;
for (int i = 0, n = boneComponents.Count; i < n; i++) {
var b = boneComponents[i];
if (b.bone == null) {
b.DoUpdate(SkeletonUtilityBone.UpdatePhase.Local);
if (b.bone == null) continue;
}
hasOverrideBones |= (b.mode == SkeletonUtilityBone.Mode.Override);
hasConstraints |= constraintTargets.Contains(b.bone);
}
hasConstraints |= constraintComponents.Count > 0;
if (skeletonAnimation != null) {
skeletonAnimation.UpdateWorld -= UpdateWorld;
skeletonAnimation.UpdateComplete -= UpdateComplete;
if (hasOverrideBones || hasConstraints)
skeletonAnimation.UpdateWorld += UpdateWorld;
if (hasConstraints)
skeletonAnimation.UpdateComplete += UpdateComplete;
}
needToReprocessBones = false;
} else {
boneComponents.Clear();
constraintComponents.Clear();
}
}
void UpdateLocal (ISkeletonAnimation anim) {
if (needToReprocessBones)
CollectBones();
var boneComponents = this.boneComponents;
if (boneComponents == null) return;
for (int i = 0, n = boneComponents.Count; i < n; i++)
boneComponents[i].transformLerpComplete = false;
UpdateAllBones(SkeletonUtilityBone.UpdatePhase.Local);
}
void UpdateWorld (ISkeletonAnimation anim) {
UpdateAllBones(SkeletonUtilityBone.UpdatePhase.World);
for (int i = 0, n = constraintComponents.Count; i < n; i++)
constraintComponents[i].DoUpdate();
}
void UpdateComplete (ISkeletonAnimation anim) {
UpdateAllBones(SkeletonUtilityBone.UpdatePhase.Complete);
}
void UpdateAllBones (SkeletonUtilityBone.UpdatePhase phase) {
if (boneRoot == null)
CollectBones();
var boneComponents = this.boneComponents;
if (boneComponents == null) return;
for (int i = 0, n = boneComponents.Count; i < n; i++)
boneComponents[i].DoUpdate(phase);
}
public Transform GetBoneRoot () {
if (boneRoot != null)
return boneRoot;
var boneRootObject = new GameObject("SkeletonUtility-SkeletonRoot");
#if UNITY_EDITOR
if (!Application.isPlaying)
UnityEditor.Undo.RegisterCreatedObjectUndo(boneRootObject, "Spawn Bone");
#endif
if (skeletonGraphic != null)
boneRootObject.AddComponent<RectTransform>();
boneRoot = boneRootObject.transform;
boneRoot.SetParent(transform);
boneRoot.localPosition = Vector3.zero;
boneRoot.localRotation = Quaternion.identity;
boneRoot.localScale = Vector3.one;
return boneRoot;
}
public GameObject SpawnRoot (SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) {
GetBoneRoot();
Skeleton skeleton = this.skeletonComponent.Skeleton;
GameObject go = SpawnBone(skeleton.RootBone, boneRoot, mode, pos, rot, sca);
CollectBones();
return go;
}
public GameObject SpawnHierarchy (SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) {
GetBoneRoot();
Skeleton skeleton = this.skeletonComponent.Skeleton;
GameObject go = SpawnBoneRecursively(skeleton.RootBone, boneRoot, mode, pos, rot, sca);
CollectBones();
return go;
}
public GameObject SpawnBoneRecursively (Bone bone, Transform parent, SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) {
GameObject go = SpawnBone(bone, parent, mode, pos, rot, sca);
ExposedList<Bone> childrenBones = bone.Children;
for (int i = 0, n = childrenBones.Count; i < n; i++) {
Bone child = childrenBones.Items[i];
SpawnBoneRecursively(child, go.transform, mode, pos, rot, sca);
}
return go;
}
public GameObject SpawnBone (Bone bone, Transform parent, SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) {
GameObject go = new GameObject(bone.Data.Name);
#if UNITY_EDITOR
if (!Application.isPlaying)
UnityEditor.Undo.RegisterCreatedObjectUndo(go, "Spawn Bone");
#endif
if (skeletonGraphic != null)
go.AddComponent<RectTransform>();
var goTransform = go.transform;
goTransform.SetParent(parent);
SkeletonUtilityBone b = go.AddComponent<SkeletonUtilityBone>();
b.hierarchy = this;
b.position = pos;
b.rotation = rot;
b.scale = sca;
b.mode = mode;
b.zPosition = true;
b.Reset();
b.bone = bone;
b.boneName = bone.Data.Name;
b.valid = true;
if (mode == SkeletonUtilityBone.Mode.Override) {
if (rot) goTransform.localRotation = Quaternion.Euler(0, 0, b.bone.AppliedRotation);
if (pos) goTransform.localPosition = new Vector3(b.bone.X * positionScale, b.bone.Y * positionScale, 0);
goTransform.localScale = new Vector3(b.bone.scaleX, b.bone.scaleY, 0);
}
return go;
}
}
}

View File

@@ -1,10 +0,0 @@
fileFormatVersion: 2
guid: 7f726fb798ad621458c431cb9966d91d
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,243 +0,0 @@
/******************************************************************************
* 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_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
#define NEW_PREFAB_SYSTEM
#endif
using UnityEngine;
namespace Spine.Unity {
/// <summary>Sets a GameObject's transform to match a bone on a Spine skeleton.</summary>
#if NEW_PREFAB_SYSTEM
[ExecuteAlways]
#else
[ExecuteInEditMode]
#endif
[AddComponentMenu("Spine/SkeletonUtilityBone")]
[HelpURL("http://esotericsoftware.com/spine-unity#SkeletonUtilityBone")]
public class SkeletonUtilityBone : MonoBehaviour {
public enum Mode {
Follow,
Override
}
public enum UpdatePhase {
Local,
World,
Complete
}
#region Inspector
/// <summary>If a bone isn't set, boneName is used to find the bone.</summary>
public string boneName;
public Transform parentReference;
public Mode mode;
public bool position, rotation, scale, zPosition = true;
[Range(0f, 1f)]
public float overrideAlpha = 1;
#endregion
public SkeletonUtility hierarchy;
[System.NonSerialized] public Bone bone;
[System.NonSerialized] public bool transformLerpComplete;
[System.NonSerialized] public bool valid;
Transform cachedTransform;
Transform skeletonTransform;
bool incompatibleTransformMode;
public bool IncompatibleTransformMode { get { return incompatibleTransformMode; } }
public void Reset () {
bone = null;
cachedTransform = transform;
valid = hierarchy != null && hierarchy.IsValid;
if (!valid)
return;
skeletonTransform = hierarchy.transform;
hierarchy.OnReset -= HandleOnReset;
hierarchy.OnReset += HandleOnReset;
DoUpdate(UpdatePhase.Local);
}
void OnEnable () {
if (hierarchy == null) hierarchy = transform.GetComponentInParent<SkeletonUtility>();
if (hierarchy == null) return;
hierarchy.RegisterBone(this);
hierarchy.OnReset += HandleOnReset;
}
void HandleOnReset () {
Reset();
}
void OnDisable () {
if (hierarchy != null) {
hierarchy.OnReset -= HandleOnReset;
hierarchy.UnregisterBone(this);
}
}
public void DoUpdate (UpdatePhase phase) {
if (!valid) {
Reset();
return;
}
var skeleton = hierarchy.Skeleton;
if (bone == null) {
if (string.IsNullOrEmpty(boneName)) return;
bone = skeleton.FindBone(boneName);
if (bone == null) {
Debug.LogError("Bone not found: " + boneName, this);
return;
}
}
if (!bone.Active) return;
float positionScale = hierarchy.PositionScale;
var thisTransform = cachedTransform;
float skeletonFlipRotation = Mathf.Sign(skeleton.ScaleX * skeleton.ScaleY);
if (mode == Mode.Follow) {
switch (phase) {
case UpdatePhase.Local:
if (position)
thisTransform.localPosition = new Vector3(bone.x * positionScale, bone.y * positionScale, 0);
if (rotation) {
if (bone.data.transformMode.InheritsRotation()) {
thisTransform.localRotation = Quaternion.Euler(0, 0, bone.rotation);
} else {
Vector3 euler = skeletonTransform.rotation.eulerAngles;
thisTransform.rotation = Quaternion.Euler(euler.x, euler.y, euler.z + (bone.WorldRotationX * skeletonFlipRotation));
}
}
if (scale) {
thisTransform.localScale = new Vector3(bone.scaleX, bone.scaleY, 1f);
incompatibleTransformMode = BoneTransformModeIncompatible(bone);
}
break;
case UpdatePhase.World:
case UpdatePhase.Complete:
// Use Applied transform values (ax, ay, AppliedRotation, ascale) if world values were modified by constraints.
if (!bone.appliedValid) {
bone.UpdateAppliedTransform();
}
if (position)
thisTransform.localPosition = new Vector3(bone.ax * positionScale, bone.ay * positionScale, 0);
if (rotation) {
if (bone.data.transformMode.InheritsRotation()) {
thisTransform.localRotation = Quaternion.Euler(0, 0, bone.AppliedRotation);
} else {
Vector3 euler = skeletonTransform.rotation.eulerAngles;
thisTransform.rotation = Quaternion.Euler(euler.x, euler.y, euler.z + (bone.WorldRotationX * skeletonFlipRotation));
}
}
if (scale) {
thisTransform.localScale = new Vector3(bone.ascaleX, bone.ascaleY, 1f);
incompatibleTransformMode = BoneTransformModeIncompatible(bone);
}
break;
}
} else if (mode == Mode.Override) {
if (transformLerpComplete)
return;
if (parentReference == null) {
if (position) {
Vector3 clp = thisTransform.localPosition / positionScale;
bone.x = Mathf.Lerp(bone.x, clp.x, overrideAlpha);
bone.y = Mathf.Lerp(bone.y, clp.y, overrideAlpha);
}
if (rotation) {
float angle = Mathf.LerpAngle(bone.Rotation, thisTransform.localRotation.eulerAngles.z, overrideAlpha);
bone.Rotation = angle;
bone.AppliedRotation = angle;
}
if (scale) {
Vector3 cls = thisTransform.localScale;
bone.scaleX = Mathf.Lerp(bone.scaleX, cls.x, overrideAlpha);
bone.scaleY = Mathf.Lerp(bone.scaleY, cls.y, overrideAlpha);
}
} else {
if (transformLerpComplete)
return;
if (position) {
Vector3 pos = parentReference.InverseTransformPoint(thisTransform.position) / positionScale;
bone.x = Mathf.Lerp(bone.x, pos.x, overrideAlpha);
bone.y = Mathf.Lerp(bone.y, pos.y, overrideAlpha);
}
if (rotation) {
float angle = Mathf.LerpAngle(bone.Rotation, Quaternion.LookRotation(Vector3.forward, parentReference.InverseTransformDirection(thisTransform.up)).eulerAngles.z, overrideAlpha);
bone.Rotation = angle;
bone.AppliedRotation = angle;
}
if (scale) {
Vector3 cls = thisTransform.localScale;
bone.scaleX = Mathf.Lerp(bone.scaleX, cls.x, overrideAlpha);
bone.scaleY = Mathf.Lerp(bone.scaleY, cls.y, overrideAlpha);
}
incompatibleTransformMode = BoneTransformModeIncompatible(bone);
}
transformLerpComplete = true;
}
}
public static bool BoneTransformModeIncompatible (Bone bone) {
return !bone.data.transformMode.InheritsScale();
}
public void AddBoundingBox (string skinName, string slotName, string attachmentName) {
SkeletonUtility.AddBoneRigidbody2D(transform.gameObject);
SkeletonUtility.AddBoundingBoxGameObject(bone.skeleton, skinName, slotName, attachmentName, transform);
}
#if UNITY_EDITOR
void OnDrawGizmos () {
if (IncompatibleTransformMode)
Gizmos.DrawIcon(transform.position + new Vector3(0, 0.128f, 0), "icon-warning");
}
#endif
}
}

View File

@@ -1,10 +0,0 @@
fileFormatVersion: 2
guid: b238dfcde8209044b97d23f62bcaadf6
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,62 +0,0 @@
/******************************************************************************
* 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_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
#define NEW_PREFAB_SYSTEM
#endif
using UnityEngine;
namespace Spine.Unity {
#if NEW_PREFAB_SYSTEM
[ExecuteAlways]
#else
[ExecuteInEditMode]
#endif
[RequireComponent(typeof(SkeletonUtilityBone))]
[HelpURL("http://esotericsoftware.com/spine-unity#SkeletonUtilityConstraint")]
public abstract class SkeletonUtilityConstraint : MonoBehaviour {
protected SkeletonUtilityBone bone;
protected SkeletonUtility hierarchy;
protected virtual void OnEnable () {
bone = GetComponent<SkeletonUtilityBone>();
hierarchy = transform.GetComponentInParent<SkeletonUtility>();
hierarchy.RegisterConstraint(this);
}
protected virtual void OnDisable () {
hierarchy.UnregisterConstraint(this);
}
public abstract void DoUpdate ();
}
}

View File

@@ -1,10 +0,0 @@
fileFormatVersion: 2
guid: 522dbfcc6c916df4396f14f35048d185
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: dfdd78a071ca1a04bb64c6cc41e14aa0
folderAsset: yes
timeCreated: 1496447038
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,230 +0,0 @@
/******************************************************************************
* 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;
using System;
namespace Spine.Unity.Deprecated {
/// <summary>
/// Deprecated. The spine-unity 3.7 runtime introduced SkeletonDataModifierAssets BlendModeMaterials which replaced SlotBlendModes. See the
/// <see href="http://esotericsoftware.com/spine-unity-skeletondatamodifierassets#BlendModeMaterials">SkeletonDataModifierAssets BlendModeMaterials documentation page</see> and
/// <see href="http://esotericsoftware.com/forum/Slot-blending-not-work-11281">this forum thread</see> for further information.
/// This class will be removed in the spine-unity 3.9 runtime.
/// </summary>
[Obsolete("The spine-unity 3.7 runtime introduced SkeletonDataModifierAssets BlendModeMaterials which replaced SlotBlendModes. Will be removed in spine-unity 3.9.", false)]
[DisallowMultipleComponent]
public class SlotBlendModes : MonoBehaviour {
#region Internal Material Dictionary
public struct MaterialTexturePair {
public Texture2D texture2D;
public Material material;
}
internal class MaterialWithRefcount {
public Material materialClone;
public int refcount = 1;
public MaterialWithRefcount(Material mat) {
this.materialClone = mat;
}
}
static Dictionary<MaterialTexturePair, MaterialWithRefcount> materialTable;
internal static Dictionary<MaterialTexturePair, MaterialWithRefcount> MaterialTable {
get {
if (materialTable == null) materialTable = new Dictionary<MaterialTexturePair, MaterialWithRefcount>();
return materialTable;
}
}
internal struct SlotMaterialTextureTuple {
public Slot slot;
public Texture2D texture2D;
public Material material;
public SlotMaterialTextureTuple(Slot slot, Material material, Texture2D texture) {
this.slot = slot;
this.material = material;
this.texture2D = texture;
}
}
internal static Material GetOrAddMaterialFor(Material materialSource, Texture2D texture) {
if (materialSource == null || texture == null) return null;
var mt = SlotBlendModes.MaterialTable;
MaterialWithRefcount matWithRefcount;
var key = new MaterialTexturePair { material = materialSource, texture2D = texture };
if (!mt.TryGetValue(key, out matWithRefcount)) {
matWithRefcount = new MaterialWithRefcount(new Material(materialSource));
var m = matWithRefcount.materialClone;
m.name = "(Clone)" + texture.name + "-" + materialSource.name;
m.mainTexture = texture;
mt[key] = matWithRefcount;
}
else {
matWithRefcount.refcount++;
}
return matWithRefcount.materialClone;
}
internal static MaterialWithRefcount GetExistingMaterialFor(Material materialSource, Texture2D texture)
{
if (materialSource == null || texture == null) return null;
var mt = SlotBlendModes.MaterialTable;
MaterialWithRefcount matWithRefcount;
var key = new MaterialTexturePair { material = materialSource, texture2D = texture };
if (!mt.TryGetValue(key, out matWithRefcount)) {
return null;
}
return matWithRefcount;
}
internal static void RemoveMaterialFromTable(Material materialSource, Texture2D texture) {
var mt = SlotBlendModes.MaterialTable;
var key = new MaterialTexturePair { material = materialSource, texture2D = texture };
mt.Remove(key);
}
#endregion
#region Inspector
public Material multiplyMaterialSource;
public Material screenMaterialSource;
Texture2D texture;
#endregion
SlotMaterialTextureTuple[] slotsWithCustomMaterial = new SlotMaterialTextureTuple[0];
public bool Applied { get; private set; }
void Start() {
if (!Applied) Apply();
}
void OnDestroy() {
if (Applied) Remove();
}
public void Apply() {
GetTexture();
if (texture == null) return;
var skeletonRenderer = GetComponent<SkeletonRenderer>();
if (skeletonRenderer == null) return;
var slotMaterials = skeletonRenderer.CustomSlotMaterials;
int numSlotsWithCustomMaterial = 0;
foreach (var s in skeletonRenderer.Skeleton.Slots) {
switch (s.data.blendMode) {
case BlendMode.Multiply:
if (multiplyMaterialSource != null) {
slotMaterials[s] = GetOrAddMaterialFor(multiplyMaterialSource, texture);
++numSlotsWithCustomMaterial;
}
break;
case BlendMode.Screen:
if (screenMaterialSource != null) {
slotMaterials[s] = GetOrAddMaterialFor(screenMaterialSource, texture);
++numSlotsWithCustomMaterial;
}
break;
}
}
slotsWithCustomMaterial = new SlotMaterialTextureTuple[numSlotsWithCustomMaterial];
int storedSlotIndex = 0;
foreach (var s in skeletonRenderer.Skeleton.Slots) {
switch (s.data.blendMode) {
case BlendMode.Multiply:
if (multiplyMaterialSource != null) {
slotsWithCustomMaterial[storedSlotIndex++] = new SlotMaterialTextureTuple(s, multiplyMaterialSource, texture);
}
break;
case BlendMode.Screen:
if (screenMaterialSource != null) {
slotsWithCustomMaterial[storedSlotIndex++] = new SlotMaterialTextureTuple(s, screenMaterialSource, texture);
}
break;
}
}
Applied = true;
skeletonRenderer.LateUpdate();
}
public void Remove() {
GetTexture();
if (texture == null) return;
var skeletonRenderer = GetComponent<SkeletonRenderer>();
if (skeletonRenderer == null) return;
var slotMaterials = skeletonRenderer.CustomSlotMaterials;
foreach (var slotWithCustomMat in slotsWithCustomMaterial) {
Slot s = slotWithCustomMat.slot;
Material storedMaterialSource = slotWithCustomMat.material;
Texture2D storedTexture = slotWithCustomMat.texture2D;
var matWithRefcount = GetExistingMaterialFor(storedMaterialSource, storedTexture);
if (--matWithRefcount.refcount == 0) {
RemoveMaterialFromTable(storedMaterialSource, storedTexture);
}
// we don't want to remove slotMaterials[s] if it has been changed in the meantime.
Material m;
if (slotMaterials.TryGetValue(s, out m)) {
var existingMat = matWithRefcount == null ? null : matWithRefcount.materialClone;
if (Material.ReferenceEquals(m, existingMat)) {
slotMaterials.Remove(s);
}
}
}
slotsWithCustomMaterial = null;
Applied = false;
if (skeletonRenderer.valid) skeletonRenderer.LateUpdate();
}
public void GetTexture() {
if (texture == null) {
var sr = GetComponent<SkeletonRenderer>(); if (sr == null) return;
var sda = sr.skeletonDataAsset; if (sda == null) return;
var aa = sda.atlasAssets[0]; if (aa == null) return;
var am = aa.PrimaryMaterial; if (am == null) return;
texture = am.mainTexture as Texture2D;
}
}
}
}

View File

@@ -1,16 +0,0 @@
fileFormatVersion: 2
guid: f1f8243645ba2e74aa3564bd956eed89
timeCreated: 1496794038
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences:
- multiplyMaterialSource: {fileID: 2100000, guid: 53bf0ab317d032d418cf1252d68f51df,
type: 2}
- screenMaterialSource: {fileID: 2100000, guid: 73f0f46d3177c614baf0fa48d646a9be,
type: 2}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,87 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: SkeletonGraphicDefault
m_Shader: {fileID: 4800000, guid: fa95b0fb6983c0f40a152e6f9aa82bfb, type: 3}
m_ShaderKeywords:
m_LightmapFlags: 5
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _AlphaTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- PixelSnap: 0
- _BumpScale: 1
- _ColorMask: 15
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _EnableExternalAlpha: 0
- _Glossiness: 0.5
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SrcBlend: 1
- _Stencil: 0
- _StencilComp: 8
- _StencilOp: 0
- _StencilReadMask: 255
- _StencilWriteMask: 255
- _UVSec: 0
- _UseUIAlphaClip: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _Flip: {r: 1, g: 1, b: 1, a: 1}
- _RendererColor: {r: 1, g: 1, b: 1, a: 1}

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: b66cf7a186d13054989b33a5c90044e4
timeCreated: 1455140322
licenseType: Free
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,95 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: SkeletonGraphicDefaultOutline
m_Shader: {fileID: 4800000, guid: 8f5d14d2a7fedb84998c50eb96c8b748, type: 3}
m_ShaderKeywords: _USE8NEIGHBOURHOOD_ON
m_LightmapFlags: 5
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _AlphaTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- PixelSnap: 0
- _BumpScale: 1
- _ColorMask: 15
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _EnableExternalAlpha: 0
- _Glossiness: 0.5
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _OutlineMipLevel: 0
- _OutlineReferenceTexWidth: 1024
- _OutlineSmoothness: 1
- _OutlineWidth: 3
- _Parallax: 0.02
- _SrcBlend: 1
- _Stencil: 0
- _StencilComp: 8
- _StencilOp: 0
- _StencilReadMask: 255
- _StencilWriteMask: 255
- _StraightAlphaInput: 0
- _ThresholdEnd: 0.25
- _UVSec: 0
- _Use8Neighbourhood: 1
- _UseUIAlphaClip: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _Flip: {r: 1, g: 1, b: 1, a: 1}
- _OutlineColor: {r: 1, g: 1, b: 0, a: 1}
- _RendererColor: {r: 1, g: 1, b: 1, a: 1}

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: c4ee0f8f4be17434aa3df5774a03b366
timeCreated: 1455140322
licenseType: Free
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,79 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: SkeletonGraphicTintBlack
m_Shader: {fileID: 4800000, guid: f64c7bc238bb2c246b8ca1912b2b6b9c, type: 3}
m_ShaderKeywords:
m_LightmapFlags: 5
m_EnableInstancingVariants: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _ColorMask: 15
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _Glossiness: 0.5
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SrcBlend: 1
- _Stencil: 0
- _StencilComp: 8
- _StencilOp: 0
- _StencilReadMask: 255
- _StencilWriteMask: 255
- _UVSec: 0
- _UseUIAlphaClip: 0
- _ZWrite: 1
m_Colors:
- _Black: {r: 0, g: 0, b: 0, a: 0}
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: cfcea0e11aa80bb4b8d05790b905fc31
timeCreated: 1455140322
licenseType: Free
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,88 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: SkeletonGraphicTintBlackOutline
m_Shader: {fileID: 4800000, guid: d55d64dd09c46af40a319933a62fa1b2, type: 3}
m_ShaderKeywords: _USE8NEIGHBOURHOOD_ON
m_LightmapFlags: 5
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _ColorMask: 15
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _Glossiness: 0.5
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _OutlineMipLevel: 0
- _OutlineReferenceTexWidth: 1024
- _OutlineSmoothness: 1
- _OutlineWidth: 3
- _Parallax: 0.02
- _SrcBlend: 1
- _Stencil: 0
- _StencilComp: 8
- _StencilOp: 0
- _StencilReadMask: 255
- _StencilWriteMask: 255
- _StraightAlphaInput: 0
- _ThresholdEnd: 0.25
- _UVSec: 0
- _Use8Neighbourhood: 1
- _UseUIAlphaClip: 0
- _ZWrite: 1
m_Colors:
- _Black: {r: 0, g: 0, b: 0, a: 0}
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _OutlineColor: {r: 1, g: 1, b: 0, a: 1}

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 94fe565c79b0aeb418cd05e4f1f8343c
timeCreated: 1455140322
licenseType: Free
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,178 +0,0 @@
/******************************************************************************
* 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.
*****************************************************************************/
// Not for optimization. Do not disable.
#define SPINE_TRIANGLECHECK // Avoid calling SetTriangles at the cost of checking for mesh differences (vertex counts, memberwise attachment list compare) every frame.
//#define SPINE_DEBUG
using UnityEngine;
using System;
using System.Collections.Generic;
namespace Spine.Unity {
/// <summary>Instructions used by a SkeletonRenderer to render a mesh.</summary>
public class SkeletonRendererInstruction {
public readonly ExposedList<SubmeshInstruction> submeshInstructions = new ExposedList<SubmeshInstruction>();
public bool immutableTriangles;
#if SPINE_TRIANGLECHECK
public bool hasActiveClipping;
public int rawVertexCount = -1;
public readonly ExposedList<Attachment> attachments = new ExposedList<Attachment>();
#endif
public void Clear () {
#if SPINE_TRIANGLECHECK
this.attachments.Clear(false);
rawVertexCount = -1;
hasActiveClipping = false;
#endif
this.submeshInstructions.Clear(false);
}
public void Dispose () {
attachments.Clear(true);
}
public void SetWithSubset (ExposedList<SubmeshInstruction> instructions, int startSubmesh, int endSubmesh) {
#if SPINE_TRIANGLECHECK
int runningVertexCount = 0;
#endif
var submeshes = this.submeshInstructions;
submeshes.Clear(false);
int submeshCount = endSubmesh - startSubmesh;
submeshes.Resize(submeshCount);
var submeshesItems = submeshes.Items;
var instructionsItems = instructions.Items;
for (int i = 0; i < submeshCount; i++) {
var instruction = instructionsItems[startSubmesh + i];
submeshesItems[i] = instruction;
#if SPINE_TRIANGLECHECK
this.hasActiveClipping |= instruction.hasClipping;
submeshesItems[i].rawFirstVertexIndex = runningVertexCount; // Ensure current instructions have correct cached values.
runningVertexCount += instruction.rawVertexCount; // vertexCount will also be used for the rest of this method.
#endif
}
#if SPINE_TRIANGLECHECK
this.rawVertexCount = runningVertexCount;
// assumption: instructions are contiguous. start and end are valid within instructions.
int startSlot = instructionsItems[startSubmesh].startSlot;
int endSlot = instructionsItems[endSubmesh - 1].endSlot;
attachments.Clear(false);
int attachmentCount = endSlot - startSlot;
attachments.Resize(attachmentCount);
var attachmentsItems = attachments.Items;
var drawOrderItems = instructionsItems[0].skeleton.drawOrder.Items;
for (int i = 0; i < attachmentCount; i++) {
Slot slot = drawOrderItems[startSlot + i];
if (!slot.bone.active) continue;
attachmentsItems[i] = slot.attachment;
}
#endif
}
public void Set (SkeletonRendererInstruction other) {
this.immutableTriangles = other.immutableTriangles;
#if SPINE_TRIANGLECHECK
this.hasActiveClipping = other.hasActiveClipping;
this.rawVertexCount = other.rawVertexCount;
this.attachments.Clear(false);
this.attachments.EnsureCapacity(other.attachments.Capacity);
this.attachments.Count = other.attachments.Count;
other.attachments.CopyTo(this.attachments.Items);
#endif
this.submeshInstructions.Clear(false);
this.submeshInstructions.EnsureCapacity(other.submeshInstructions.Capacity);
this.submeshInstructions.Count = other.submeshInstructions.Count;
other.submeshInstructions.CopyTo(this.submeshInstructions.Items);
}
public static bool GeometryNotEqual (SkeletonRendererInstruction a, SkeletonRendererInstruction b) {
#if SPINE_TRIANGLECHECK
#if UNITY_EDITOR
if (!Application.isPlaying)
return true;
#endif
if (a.hasActiveClipping || b.hasActiveClipping) return true; // Triangles are unpredictable when clipping is active.
// Everything below assumes the raw vertex and triangle counts were used. (ie, no clipping was done)
if (a.rawVertexCount != b.rawVertexCount) return true;
if (a.immutableTriangles != b.immutableTriangles) return true;
int attachmentCountB = b.attachments.Count;
if (a.attachments.Count != attachmentCountB) return true; // Bounds check for the looped storedAttachments count below.
// Submesh count changed
int submeshCountA = a.submeshInstructions.Count;
int submeshCountB = b.submeshInstructions.Count;
if (submeshCountA != submeshCountB) return true;
// Submesh Instruction mismatch
var submeshInstructionsItemsA = a.submeshInstructions.Items;
var submeshInstructionsItemsB = b.submeshInstructions.Items;
var attachmentsA = a.attachments.Items;
var attachmentsB = b.attachments.Items;
for (int i = 0; i < attachmentCountB; i++)
if (!System.Object.ReferenceEquals(attachmentsA[i], attachmentsB[i])) return true;
for (int i = 0; i < submeshCountB; i++) {
var submeshA = submeshInstructionsItemsA[i];
var submeshB = submeshInstructionsItemsB[i];
if (!(
submeshA.rawVertexCount == submeshB.rawVertexCount &&
submeshA.startSlot == submeshB.startSlot &&
submeshA.endSlot == submeshB.endSlot
&& submeshA.rawTriangleCount == submeshB.rawTriangleCount &&
submeshA.rawFirstVertexIndex == submeshB.rawFirstVertexIndex
))
return true;
}
return false;
#else
// In normal immutable triangle use, immutableTriangles will be initially false, forcing the smartmesh to update the first time but never again after that, unless there was an immutableTriangles flag mismatch..
if (a.immutableTriangles || b.immutableTriangles)
return (a.immutableTriangles != b.immutableTriangles);
return true;
#endif
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: d07866ade25bd0b44a7bb1d59bacf4cb
timeCreated: 1563322425
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,4 +0,0 @@
fileFormatVersion: 2
guid: ef8189a68a74bec4eba582e65fb98dbd
DefaultImporter:
userData:

View File

@@ -1,128 +0,0 @@
// Spine/Skeleton PMA Screen
// - single color multiply tint
// - unlit
// - Premultiplied alpha Multiply blending
// - No depth, no backface culling, no fog.
// - ShadowCaster pass
Shader "Spine/Blend Modes/Skeleton PMA Additive" {
Properties {
_Color ("Tint Color", Color) = (1,1,1,1)
[NoScaleOffset] _MainTex ("MainTex", 2D) = "black" {}
[Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0
_Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1
[HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0
[HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default
// Outline properties are drawn via custom editor.
[HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0
[HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1)
[HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024
[HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25
[HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0
[HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1
[HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }
LOD 100
Fog { Mode Off }
Cull Off
ZWrite Off
Blend One One
Lighting Off
Stencil {
Ref[_StencilRef]
Comp[_StencilComp]
Pass Keep
}
Pass {
Name "Normal"
CGPROGRAM
#pragma shader_feature _ _STRAIGHT_ALPHA_INPUT
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
uniform sampler2D _MainTex;
uniform float4 _Color;
struct VertexInput {
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float4 vertexColor : COLOR;
};
struct VertexOutput {
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
float4 vertexColor : COLOR;
};
VertexOutput vert (VertexInput v) {
VertexOutput o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
o.vertexColor = v.vertexColor * float4(_Color.rgb * _Color.a, _Color.a); // Combine a PMA version of _Color with vertexColor.
return o;
}
float4 frag (VertexOutput i) : SV_Target {
float4 texColor = tex2D(_MainTex, i.uv);
#if defined(_STRAIGHT_ALPHA_INPUT)
texColor.rgb *= texColor.a;
#endif
return (texColor * i.vertexColor);
}
ENDCG
}
Pass {
Name "Caster"
Tags { "LightMode"="ShadowCaster" }
Offset 1, 1
ZWrite On
ZTest LEqual
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_shadowcaster
#pragma fragmentoption ARB_precision_hint_fastest
#include "UnityCG.cginc"
struct v2f {
V2F_SHADOW_CASTER;
float4 uvAndAlpha : TEXCOORD1;
};
uniform float4 _MainTex_ST;
v2f vert (appdata_base v, float4 vertexColor : COLOR) {
v2f o;
TRANSFER_SHADOW_CASTER(o)
o.uvAndAlpha.xy = TRANSFORM_TEX(v.texcoord, _MainTex);
o.uvAndAlpha.z = 0;
o.uvAndAlpha.a = vertexColor.a;
return o;
}
uniform sampler2D _MainTex;
uniform fixed _Cutoff;
float4 frag (v2f i) : SV_Target {
fixed4 texcol = tex2D(_MainTex, i.uvAndAlpha.xy);
clip(texcol.a * i.uvAndAlpha.a - _Cutoff);
SHADOW_CASTER_FRAGMENT(i)
}
ENDCG
}
}
CustomEditor "SpineShaderWithOutlineGUI"
}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 53efa1d97f5d9f74285d4330cda14e36
timeCreated: 1496446742
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,41 +0,0 @@
#ifndef SPRITES_DEPTH_ONLY_PASS_INCLUDED
#define SPRITES_DEPTH_ONLY_PASS_INCLUDED
#include "UnityCG.cginc"
sampler2D _MainTex;
float _Cutoff;
float _ZWriteOffset;
struct VertexInput {
float4 positionOS : POSITION;
float2 texcoord : TEXCOORD0;
float4 vertexColor : COLOR;
};
struct VertexOutput {
float4 positionCS : SV_POSITION;
float4 texcoordAndAlpha: TEXCOORD0;
};
VertexOutput DepthOnlyVertex (VertexInput v) {
VertexOutput o;
o.positionCS = UnityObjectToClipPos(v.positionOS - float4(0, 0, _ZWriteOffset, 0));
o.texcoordAndAlpha.xy = v.texcoord;
o.texcoordAndAlpha.z = 0;
o.texcoordAndAlpha.a = v.vertexColor.a;
return o;
}
float4 DepthOnlyFragment (VertexOutput input) : SV_Target{
float4 texColor = tex2D(_MainTex, input.texcoordAndAlpha.rg);
#if defined(_STRAIGHT_ALPHA_INPUT)
texColor.rgb *= texColor.a;
#endif
clip(texColor.a * input.texcoordAndAlpha.a - _Cutoff);
return 0;
}
#endif

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 27351ce55d3beb643ae8d9385db21941
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,42 +0,0 @@
#ifndef SPINE_OUTLINE_COMMON_INCLUDED
#define SPINE_OUTLINE_COMMON_INCLUDED
float4 computeOutlinePixel(sampler2D mainTexture, float2 mainTextureTexelSize,
float2 uv, float vertexColorAlpha,
float OutlineWidth, float OutlineReferenceTexWidth, float OutlineMipLevel,
float OutlineSmoothness, float ThresholdEnd, float4 OutlineColor) {
float4 texColor = fixed4(0, 0, 0, 0);
float outlineWidthCompensated = OutlineWidth / (OutlineReferenceTexWidth * mainTextureTexelSize.x);
float xOffset = mainTextureTexelSize.x * outlineWidthCompensated;
float yOffset = mainTextureTexelSize.y * outlineWidthCompensated;
float xOffsetDiagonal = mainTextureTexelSize.x * outlineWidthCompensated * 0.7;
float yOffsetDiagonal = mainTextureTexelSize.y * outlineWidthCompensated * 0.7;
float pixelCenter = tex2D(mainTexture, uv).a;
float4 uvCenterWithLod = float4(uv, 0, OutlineMipLevel);
float pixelTop = tex2Dlod(mainTexture, uvCenterWithLod + float4(0, yOffset, 0, 0)).a;
float pixelBottom = tex2Dlod(mainTexture, uvCenterWithLod + float4(0, -yOffset, 0, 0)).a;
float pixelLeft = tex2Dlod(mainTexture, uvCenterWithLod + float4(-xOffset, 0, 0, 0)).a;
float pixelRight = tex2Dlod(mainTexture, uvCenterWithLod + float4(xOffset, 0, 0, 0)).a;
#if _USE8NEIGHBOURHOOD_ON
float numSamples = 8;
float pixelTopLeft = tex2Dlod(mainTexture, uvCenterWithLod + float4(-xOffsetDiagonal, yOffsetDiagonal, 0, 0)).a;
float pixelTopRight = tex2Dlod(mainTexture, uvCenterWithLod + float4(xOffsetDiagonal, yOffsetDiagonal, 0, 0)).a;
float pixelBottomLeft = tex2Dlod(mainTexture, uvCenterWithLod + float4(-xOffsetDiagonal, -yOffsetDiagonal, 0, 0)).a;
float pixelBottomRight = tex2Dlod(mainTexture, uvCenterWithLod + float4(xOffsetDiagonal, -yOffsetDiagonal, 0, 0)).a;
float average = (pixelTop + pixelBottom + pixelLeft + pixelRight +
pixelTopLeft + pixelTopRight + pixelBottomLeft + pixelBottomRight)
* vertexColorAlpha / numSamples;
#else // 4 neighbourhood
float numSamples = 1;
float average = (pixelTop + pixelBottom + pixelLeft + pixelRight) * vertexColorAlpha / numSamples;
#endif
float thresholdStart = ThresholdEnd * (1.0 - OutlineSmoothness);
float outlineAlpha = saturate((average - thresholdStart) / (ThresholdEnd - thresholdStart)) - pixelCenter;
return lerp(texColor, OutlineColor, outlineAlpha);
}
#endif

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: a8d610b87be4e82409e18a63a930d335
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,30 +0,0 @@
#ifndef SKELETON_LIT_COMMON_SHADOW_INCLUDED
#define SKELETON_LIT_COMMON_SHADOW_INCLUDED
#include "UnityCG.cginc"
struct v2f {
V2F_SHADOW_CASTER;
float4 uvAndAlpha : TEXCOORD1;
};
uniform float4 _MainTex_ST;
v2f vertShadow(appdata_base v, float4 vertexColor : COLOR) {
v2f o;
TRANSFER_SHADOW_CASTER(o)
o.uvAndAlpha.xy = TRANSFORM_TEX(v.texcoord, _MainTex);
o.uvAndAlpha.z = 0;
o.uvAndAlpha.a = vertexColor.a;
return o;
}
uniform sampler2D _MainTex;
uniform fixed SHADOW_CUTOFF;
float4 fragShadow (v2f i) : SV_Target {
fixed4 texcol = tex2D(_MainTex, i.uvAndAlpha.xy);
clip(texcol.a * i.uvAndAlpha.a - SHADOW_CUTOFF);
SHADOW_CASTER_FRAGMENT(i)
}
#endif

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: c7297b25c81d2494e8e73b742e3c7345
timeCreated: 1564083752
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,120 +0,0 @@
#ifndef SKELETON_LIT_COMMON_INCLUDED
#define SKELETON_LIT_COMMON_INCLUDED
#include "UnityCG.cginc"
// ES2.0/WebGL/3DS can not do loops with non-constant-expression iteration counts :(
#if defined(SHADER_API_GLES)
#define LIGHT_LOOP_LIMIT 8
#elif defined(SHADER_API_N3DS)
#define LIGHT_LOOP_LIMIT 4
#else
#define LIGHT_LOOP_LIMIT unity_VertexLightParams.x
#endif
////////////////////////////////////////
// Alpha Clipping
//
#if defined(_ALPHA_CLIP)
uniform fixed _Cutoff;
#define ALPHA_CLIP(pixel, color) clip((pixel.a * color.a) - _Cutoff);
#else
#define ALPHA_CLIP(pixel, color)
#endif
half3 computeLighting (int idx, half3 dirToLight, half3 eyeNormal, half4 diffuseColor, half atten) {
half NdotL = max(dot(eyeNormal, dirToLight), 0.0);
// diffuse
half3 color = NdotL * diffuseColor.rgb * unity_LightColor[idx].rgb;
return color * atten;
}
half3 computeOneLight (int idx, float3 eyePosition, half3 eyeNormal, half4 diffuseColor) {
float3 dirToLight = unity_LightPosition[idx].xyz;
half att = 1.0;
#if defined(POINT) || defined(SPOT)
dirToLight -= eyePosition * unity_LightPosition[idx].w;
// distance attenuation
float distSqr = dot(dirToLight, dirToLight);
att /= (1.0 + unity_LightAtten[idx].z * distSqr);
if (unity_LightPosition[idx].w != 0 && distSqr > unity_LightAtten[idx].w) att = 0.0; // set to 0 if outside of range
distSqr = max(distSqr, 0.000001); // don't produce NaNs if some vertex position overlaps with the light
dirToLight *= rsqrt(distSqr);
#if defined(SPOT)
// spot angle attenuation
half rho = max(dot(dirToLight, unity_SpotDirection[idx].xyz), 0.0);
half spotAtt = (rho - unity_LightAtten[idx].x) * unity_LightAtten[idx].y;
att *= saturate(spotAtt);
#endif
#endif
att *= 0.5; // passed in light colors are 2x brighter than what used to be in FFP
return min (computeLighting (idx, dirToLight, eyeNormal, diffuseColor, att), 1.0);
}
int4 unity_VertexLightParams; // x: light count, y: zero, z: one (y/z needed by d3d9 vs loop instruction)
struct appdata {
float3 pos : POSITION;
float3 normal : NORMAL;
half4 color : COLOR;
float2 uv0 : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct VertexOutput {
fixed4 color : COLOR0;
float2 uv0 : TEXCOORD0;
float4 pos : SV_POSITION;
UNITY_VERTEX_OUTPUT_STEREO
};
VertexOutput vert (appdata v) {
VertexOutput o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
half4 color = v.color;
float3 eyePos = UnityObjectToViewPos(float4(v.pos, 1)).xyz; //mul(UNITY_MATRIX_MV, float4(v.pos,1)).xyz;
half3 fixedNormal = half3(0,0,-1);
half3 eyeNormal = normalize(mul((float3x3)UNITY_MATRIX_IT_MV, fixedNormal));
#ifdef _DOUBLE_SIDED_LIGHTING
// unfortunately we have to compute the sign here in the vertex shader
// instead of using VFACE in fragment shader stage.
half faceSign = sign(eyeNormal.z);
eyeNormal *= faceSign;
#endif
// Lights
half3 lcolor = half4(0,0,0,1).rgb + color.rgb * glstate_lightmodel_ambient.rgb;
for (int il = 0; il < LIGHT_LOOP_LIMIT; ++il) {
lcolor += computeOneLight(il, eyePos, eyeNormal, color);
}
color.rgb = lcolor.rgb;
o.color = saturate(color);
o.uv0 = v.uv0;
o.pos = UnityObjectToClipPos(v.pos);
return o;
}
sampler2D _MainTex;
fixed4 frag (VertexOutput i) : SV_Target {
fixed4 tex = tex2D(_MainTex, i.uv0);
ALPHA_CLIP(tex, i.color);
#if defined(_STRAIGHT_ALPHA_INPUT)
tex.rgb *= tex.a;
#endif
fixed4 col = tex * i.color;
col.rgb *= 2;
return col;
}
#endif

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 70c77c02aabd5e44f94aab48dd0be7b2
timeCreated: 1564083752
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,46 +0,0 @@
// Outline shader variant of "Spine/Blend Modes/Skeleton PMA Additive"
Shader "Spine/Outline/Blend Modes/Skeleton PMA Additive" {
Properties {
_Color ("Tint Color", Color) = (1,1,1,1)
[NoScaleOffset] _MainTex ("MainTex", 2D) = "black" {}
[Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0
_Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1
[HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0
[HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default
// Outline properties are drawn via custom editor.
[HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0
[HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1)
[HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024
[HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25
[HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0
[HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1
[HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }
LOD 100
Fog { Mode Off }
Cull Off
ZWrite Off
Blend One One
Lighting Off
Stencil {
Ref[_StencilRef]
Comp[_StencilComp]
Pass Keep
}
UsePass "Spine/Outline/Skeleton/OUTLINE"
UsePass "Spine/Blend Modes/Skeleton PMA Additive/NORMAL"
UsePass "Spine/Blend Modes/Skeleton PMA Additive/CASTER"
}
FallBack "Spine/Blend Modes/Skeleton PMA Additive"
CustomEditor "SpineShaderWithOutlineGUI"
}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 0299ffae826705448b6c80ccc6a53b75
timeCreated: 1573829476
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,46 +0,0 @@
// Outline shader variant of "Spine/Blend Modes/Skeleton PMA Multiply"
Shader "Spine/Outline/Blend Modes/Skeleton PMA Multiply" {
Properties {
_Color ("Tint Color", Color) = (1,1,1,1)
[NoScaleOffset] _MainTex ("MainTex", 2D) = "black" {}
[Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0
_Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1
[HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0
[HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default
// Outline properties are drawn via custom editor.
[HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0
[HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1)
[HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024
[HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25
[HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0
[HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1
[HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }
LOD 100
Fog { Mode Off }
Cull Off
ZWrite Off
Blend DstColor OneMinusSrcAlpha
Lighting Off
Stencil {
Ref[_StencilRef]
Comp[_StencilComp]
Pass Keep
}
UsePass "Spine/Outline/Skeleton/OUTLINE"
UsePass "Spine/Blend Modes/Skeleton PMA Multiply/NORMAL"
UsePass "Spine/Blend Modes/Skeleton PMA Multiply/CASTER"
}
FallBack "Spine/Blend Modes/Skeleton PMA Multiply"
CustomEditor "SpineShaderWithOutlineGUI"
}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 4b3566a937643b8498d1ec6df5880b77
timeCreated: 1573829476
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,92 +0,0 @@
#ifndef SPINE_OUTLINE_PASS_INCLUDED
#define SPINE_OUTLINE_PASS_INCLUDED
#include "UnityCG.cginc"
#ifdef SKELETON_GRAPHIC
#include "UnityUI.cginc"
#endif
#include "../../CGIncludes/Spine-Outline-Common.cginc"
sampler2D _MainTex;
float _OutlineWidth;
float4 _OutlineColor;
float4 _MainTex_TexelSize;
float _ThresholdEnd;
float _OutlineSmoothness;
float _OutlineMipLevel;
int _OutlineReferenceTexWidth;
#ifdef SKELETON_GRAPHIC
float4 _ClipRect;
#endif
struct VertexInput {
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float4 vertexColor : COLOR;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct VertexOutput {
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
float vertexColorAlpha : COLOR;
#ifdef SKELETON_GRAPHIC
float4 worldPosition : TEXCOORD1;
#endif
UNITY_VERTEX_OUTPUT_STEREO
};
#ifdef SKELETON_GRAPHIC
VertexOutput vertOutlineGraphic(VertexInput v) {
VertexOutput o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.worldPosition = v.vertex;
o.pos = UnityObjectToClipPos(o.worldPosition);
o.uv = v.uv;
#ifdef UNITY_HALF_TEXEL_OFFSET
o.pos.xy += (_ScreenParams.zw - 1.0) * float2(-1, 1);
#endif
o.vertexColorAlpha = v.vertexColor.a;
return o;
}
#else // !SKELETON_GRAPHIC
VertexOutput vertOutline(VertexInput v) {
VertexOutput o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
o.vertexColorAlpha = v.vertexColor.a;
return o;
}
#endif
float4 fragOutline(VertexOutput i) : SV_Target {
float4 texColor = computeOutlinePixel(_MainTex, _MainTex_TexelSize.xy, i.uv, i.vertexColorAlpha,
_OutlineWidth, _OutlineReferenceTexWidth, _OutlineMipLevel,
_OutlineSmoothness, _ThresholdEnd, _OutlineColor);
#ifdef SKELETON_GRAPHIC
texColor *= UnityGet2DClipping(i.worldPosition.xy, _ClipRect);
#endif
return texColor;
}
#endif // SPINE_OUTLINE_PASS_INCLUDED

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 2ec781e799f97504c8a418e168759f70
timeCreated: 1574096529
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 6e8ed065898e65f4d9303492725fb912
folderAsset: yes
timeCreated: 1573829873
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,43 +0,0 @@
// Outline shader variant of "Spine/Skeleton Fill"
Shader "Spine/Outline/Skeleton Fill" {
Properties {
_FillColor ("FillColor", Color) = (1,1,1,1)
_FillPhase ("FillPhase", Range(0, 1)) = 0
[NoScaleOffset] _MainTex ("MainTex", 2D) = "white" {}
_Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1
[Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0
[HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0
[HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default
// Outline properties are drawn via custom editor.
[HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0
[HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1)
[HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024
[HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25
[HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0
[HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1
[HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" }
Blend One OneMinusSrcAlpha
Cull Off
ZWrite Off
Lighting Off
Stencil {
Ref[_StencilRef]
Comp[_StencilComp]
Pass Keep
}
UsePass "Spine/Outline/Skeleton/OUTLINE"
UsePass "Spine/Skeleton Fill/NORMAL"
UsePass "Spine/Skeleton Fill/CASTER"
}
FallBack "Spine/Skeleton Fill"
CustomEditor "SpineShaderWithOutlineGUI"
}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: e158cbe58baa093438feb3d691f3daba
timeCreated: 1573817434
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,40 +0,0 @@
// Outline shader variant of "Spine/Skeleton Lit"
Shader "Spine/Outline/Skeleton Lit" {
Properties {
_Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1
[NoScaleOffset] _MainTex ("Main Texture", 2D) = "black" {}
[Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0
[Toggle(_DOUBLE_SIDED_LIGHTING)] _DoubleSidedLighting("Double-Sided Lighting", Int) = 0
[HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0
[HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default
// Outline properties are drawn via custom editor.
[HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0
[HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1)
[HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024
[HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25
[HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0
[HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1
[HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }
LOD 100
Stencil {
Ref[_StencilRef]
Comp[_StencilComp]
Pass Keep
}
UsePass "Spine/Outline/Skeleton/OUTLINE"
UsePass "Spine/Skeleton Lit/NORMAL"
UsePass "Spine/Skeleton Lit/CASTER"
}
FallBack "Spine/Skeleton Lit"
CustomEditor "SpineShaderWithOutlineGUI"
}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 10fab3f69a099be4391fe8a1ad880c65
timeCreated: 1573828963
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,41 +0,0 @@
// Outline shader variant of "Spine/Skeleton Lit ZWrite"
Shader "Spine/Outline/Skeleton Lit ZWrite" {
Properties {
_Cutoff ("Depth alpha cutoff", Range(0,1)) = 0.1
_ShadowAlphaCutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1
[NoScaleOffset] _MainTex ("Main Texture", 2D) = "black" {}
[Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0
[Toggle(_DOUBLE_SIDED_LIGHTING)] _DoubleSidedLighting("Double-Sided Lighting", Int) = 0
[HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0
[HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default
// Outline properties are drawn via custom editor.
[HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0
[HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1)
[HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024
[HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25
[HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0
[HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1
[HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }
LOD 100
Stencil {
Ref[_StencilRef]
Comp[_StencilComp]
Pass Keep
}
UsePass "Spine/Outline/Skeleton/OUTLINE"
UsePass "Spine/Skeleton Lit ZWrite/NORMAL"
UsePass "Spine/Skeleton Lit ZWrite/CASTER"
}
FallBack "Spine/Skeleton Lit ZWrite"
CustomEditor "SpineShaderWithOutlineGUI"
}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 756be4f2f738f6c4583bb1c90e16bf0b
timeCreated: 1573828964
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,52 +0,0 @@
// Outline shader variant of "Spine/Skeleton"
Shader "Spine/Outline/Skeleton" {
Properties {
_Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1
[NoScaleOffset] _MainTex ("Main Texture", 2D) = "black" {}
[Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0
[HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0
[HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default
// Outline properties are drawn via custom editor.
[HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0
[HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1)
[HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024
[HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25
[HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0
[HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1
[HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" }
Fog { Mode Off }
Cull Off
ZWrite Off
Blend One OneMinusSrcAlpha
Lighting Off
Stencil {
Ref[_StencilRef]
Comp[_StencilComp]
Pass Keep
}
Pass {
Name "Outline"
CGPROGRAM
#pragma vertex vertOutline
#pragma fragment fragOutline
#pragma shader_feature _ _USE8NEIGHBOURHOOD_ON
#include "CGIncludes/Spine-Outline-Pass.cginc"
ENDCG
}
UsePass "Spine/Skeleton/NORMAL"
UsePass "Spine/Skeleton/CASTER"
}
FallBack "Spine/Skeleton"
CustomEditor "SpineShaderWithOutlineGUI"
}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 28b5cf4804845fe4b868531fd0bb81d5
timeCreated: 1573817434
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,62 +0,0 @@
Shader "Spine/Outline/OutlineOnly-ZWrite" {
Properties {
_Cutoff ("Depth alpha cutoff", Range(0,1)) = 0.1
_ZWriteOffset ("Depth offset", Range(0,1)) = 0.01
[NoScaleOffset] _MainTex ("Main Texture", 2D) = "black" {}
[Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0
[HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0
[HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default
// Outline properties are drawn via custom editor.
[HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0
[HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1)
[HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024
[HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25
[HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0
[HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1
[HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" }
Fog { Mode Off }
Cull Off
ZWrite Off
Blend One OneMinusSrcAlpha
Lighting Off
Stencil {
Ref[_StencilRef]
Comp[_StencilComp]
Pass Keep
}
Pass
{
Name "DepthOnly"
ZWrite On
ColorMask 0
Cull Off
CGPROGRAM
#pragma vertex DepthOnlyVertex
#pragma fragment DepthOnlyFragment
#include "../CGIncludes/Spine-DepthOnlyPass.cginc"
ENDCG
}
Pass {
Name "Outline"
CGPROGRAM
#pragma vertex vertOutline
#pragma fragment fragOutline
#pragma shader_feature _ _USE8NEIGHBOURHOOD_ON
#include "CGIncludes/Spine-Outline-Pass.cginc"
ENDCG
}
}
FallBack "Spine/Skeleton"
CustomEditor "SpineShaderWithOutlineGUI"
}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 177da18c3d2e0aa4cb39990ea011973c
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 7a42d52714848d64f8ff99dddb93500e
folderAsset: yes
timeCreated: 1563289150
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,126 +0,0 @@
// - Unlit
// - Premultiplied Alpha Blending (Optional straight alpha input)
// - Double-sided, no depth
Shader "Spine/Skeleton Fill" {
Properties {
_FillColor ("FillColor", Color) = (1,1,1,1)
_FillPhase ("FillPhase", Range(0, 1)) = 0
[NoScaleOffset] _MainTex ("MainTex", 2D) = "white" {}
_Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1
[Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0
[HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0
[HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default
// Outline properties are drawn via custom editor.
[HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0
[HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1)
[HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024
[HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25
[HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0
[HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1
[HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" }
Blend One OneMinusSrcAlpha
Cull Off
ZWrite Off
Lighting Off
Stencil {
Ref[_StencilRef]
Comp[_StencilComp]
Pass Keep
}
Pass {
Name "Normal"
CGPROGRAM
#pragma shader_feature _ _STRAIGHT_ALPHA_INPUT
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _MainTex;
float4 _FillColor;
float _FillPhase;
struct VertexInput {
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float4 vertexColor : COLOR;
};
struct VertexOutput {
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
float4 vertexColor : COLOR;
};
VertexOutput vert (VertexInput v) {
VertexOutput o = (VertexOutput)0;
o.uv = v.uv;
o.vertexColor = v.vertexColor;
o.pos = UnityObjectToClipPos(v.vertex);
return o;
}
float4 frag (VertexOutput i) : SV_Target {
float4 rawColor = tex2D(_MainTex,i.uv);
float finalAlpha = (rawColor.a * i.vertexColor.a);
#if defined(_STRAIGHT_ALPHA_INPUT)
rawColor.rgb *= rawColor.a;
#endif
float3 finalColor = lerp((rawColor.rgb * i.vertexColor.rgb), (_FillColor.rgb * finalAlpha), _FillPhase); // make sure to PMA _FillColor.
return fixed4(finalColor, finalAlpha);
}
ENDCG
}
Pass {
Name "Caster"
Tags { "LightMode"="ShadowCaster" }
Offset 1, 1
ZWrite On
ZTest LEqual
Fog { Mode Off }
Cull Off
Lighting Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_shadowcaster
#pragma fragmentoption ARB_precision_hint_fastest
#include "UnityCG.cginc"
sampler2D _MainTex;
fixed _Cutoff;
struct VertexOutput {
V2F_SHADOW_CASTER;
float4 uvAndAlpha : TEXCOORD1;
};
VertexOutput vert (appdata_base v, float4 vertexColor : COLOR) {
VertexOutput o;
o.uvAndAlpha = v.texcoord;
o.uvAndAlpha.a = vertexColor.a;
TRANSFER_SHADOW_CASTER(o)
return o;
}
float4 frag (VertexOutput i) : SV_Target {
fixed4 texcol = tex2D(_MainTex, i.uvAndAlpha.xy);
clip(texcol.a * i.uvAndAlpha.a - _Cutoff);
SHADOW_CASTER_FRAGMENT(i)
}
ENDCG
}
}
FallBack "Diffuse"
CustomEditor "SpineShaderWithOutlineGUI"
}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 45495790b394f894a967dbf44489b57b
timeCreated: 1492385797
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,82 +0,0 @@
// - Vertex Lit + ShadowCaster
// - Premultiplied Alpha Blending (Optional straight alpha input)
// - Double-sided, ZWrite
Shader "Spine/Skeleton Lit ZWrite" {
Properties {
_Cutoff ("Depth alpha cutoff", Range(0,1)) = 0.1
_ShadowAlphaCutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1
[NoScaleOffset] _MainTex ("Main Texture", 2D) = "black" {}
[Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0
[Toggle(_DOUBLE_SIDED_LIGHTING)] _DoubleSidedLighting("Double-Sided Lighting", Int) = 0
[HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0
[HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default
// Outline properties are drawn via custom editor.
[HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0
[HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1)
[HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024
[HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25
[HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0
[HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1
[HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }
LOD 100
Stencil {
Ref[_StencilRef]
Comp[_StencilComp]
Pass Keep
}
Pass {
Name "Normal"
Tags { "LightMode"="Vertex" "Queue"="Transparent" "IgnoreProjector"="true" "RenderType"="Transparent" }
ZWrite On
Cull Off
Blend One OneMinusSrcAlpha
CGPROGRAM
#pragma shader_feature _ _STRAIGHT_ALPHA_INPUT
#pragma shader_feature _ _DOUBLE_SIDED_LIGHTING
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#define _ALPHA_CLIP
#pragma multi_compile __ POINT SPOT
#include "CGIncludes/Spine-Skeleton-Lit-Common.cginc"
ENDCG
}
Pass {
Name "Caster"
Tags { "LightMode"="ShadowCaster" }
Offset 1, 1
Fog { Mode Off }
ZWrite On
ZTest LEqual
Cull Off
Lighting Off
CGPROGRAM
#pragma vertex vertShadow
#pragma fragment fragShadow
#pragma multi_compile_shadowcaster
#pragma fragmentoption ARB_precision_hint_fastest
#define SHADOW_CUTOFF _ShadowAlphaCutoff
#include "CGIncludes/Spine-Skeleton-Lit-Common-Shadow.cginc"
ENDCG
}
}
CustomEditor "SpineShaderWithOutlineGUI"
}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: fde05abf1f7be4b4da1caf8c8de1823a
timeCreated: 1564082883
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,80 +0,0 @@
// - Vertex Lit + ShadowCaster
// - Premultiplied Alpha Blending (Optional straight alpha input)
// - Double-sided, no depth
Shader "Spine/Skeleton Lit" {
Properties {
_Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1
[NoScaleOffset] _MainTex ("Main Texture", 2D) = "black" {}
[Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0
[Toggle(_DOUBLE_SIDED_LIGHTING)] _DoubleSidedLighting("Double-Sided Lighting", Int) = 0
[HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0
[HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default
// Outline properties are drawn via custom editor.
[HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0
[HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1)
[HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024
[HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25
[HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0
[HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1
[HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }
LOD 100
Stencil {
Ref[_StencilRef]
Comp[_StencilComp]
Pass Keep
}
Pass {
Name "Normal"
Tags { "LightMode"="Vertex" "Queue"="Transparent" "IgnoreProjector"="true" "RenderType"="Transparent" }
ZWrite Off
Cull Off
Blend One OneMinusSrcAlpha
CGPROGRAM
#pragma shader_feature _ _STRAIGHT_ALPHA_INPUT
#pragma shader_feature _ _DOUBLE_SIDED_LIGHTING
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#pragma multi_compile __ POINT SPOT
#include "CGIncludes/Spine-Skeleton-Lit-Common.cginc"
ENDCG
}
Pass {
Name "Caster"
Tags { "LightMode"="ShadowCaster" }
Offset 1, 1
Fog { Mode Off }
ZWrite On
ZTest LEqual
Cull Off
Lighting Off
CGPROGRAM
#pragma vertex vertShadow
#pragma fragment fragShadow
#pragma multi_compile_shadowcaster
#pragma fragmentoption ARB_precision_hint_fastest
#define SHADOW_CUTOFF _Cutoff
#include "CGIncludes/Spine-Skeleton-Lit-Common-Shadow.cginc"
ENDCG
}
}
CustomEditor "SpineShaderWithOutlineGUI"
}

View File

@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: bd83c75f51f5e23498ae22ffcdfe92c3
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,76 +0,0 @@
#ifndef SHADER_MATHS_INCLUDED
#define SHADER_MATHS_INCLUDED
#if defined(USE_LWRP)
#include "Packages/com.unity.render-pipelines.lightweight/ShaderLibrary/Core.hlsl"
#elif defined(USE_URP)
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#else
#include "UnityCG.cginc"
#endif
////////////////////////////////////////
// Maths functions
//
inline half3 safeNormalize(half3 inVec)
{
half dp3 = max(0.001f, dot(inVec, inVec));
return inVec * rsqrt(dp3);
}
inline float dotClamped(float3 a, float3 b)
{
#if (SHADER_TARGET < 30 || defined(SHADER_API_PS3))
return saturate(dot(a, b));
#else
return max(0.0h, dot(a, b));
#endif
}
inline float oneDividedBy(float value)
{
//Catches NANs
float sign_value = sign(value);
float sign_value_squared = sign_value*sign_value;
return sign_value_squared / ( value + sign_value_squared - 1.0);
}
inline half pow5 (half x)
{
return x*x*x*x*x;
}
inline float4 quat_from_axis_angle(float3 axis, float angleRadians)
{
float4 qr;
float half_angle = (angleRadians * 0.5);
qr.x = axis.x * sin(half_angle);
qr.y = axis.y * sin(half_angle);
qr.z = axis.z * sin(half_angle);
qr.w = cos(half_angle);
return qr;
}
inline float3 rotate_vertex_position(float3 position, float3 axis, float angleRadians)
{
float4 q = quat_from_axis_angle(axis, angleRadians);
float3 v = position.xyz;
return v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v);
}
float3 EncodeFloatRGB(float value)
{
const float max24int = 256*256*256-1;
float3 decomp = floor( value * float3( max24int/(256*256), max24int/256, max24int ) ) / 255.0;
decomp.z -= decomp.y * 256.0;
decomp.y -= decomp.x * 256.0;
return decomp;
}
float DecodeFloatRGB(float3 decomp)
{
return dot( decomp.xyz, float3( 255.0/256, 255.0/(256*256), 255.0/(256*256*256) ) );
}
#endif // SHADER_MATHS_INCLUDED

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: e1de23de2025abe4a84ff2edd3f24491
timeCreated: 1494092582
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,417 +0,0 @@
// Upgrade NOTE: upgraded instancing buffer 'PerDrawSprite' to new syntax.
#ifndef SHADER_SHARED_INCLUDED
#define SHADER_SHARED_INCLUDED
#if defined(USE_LWRP)
#include "Packages/com.unity.render-pipelines.lightweight/ShaderLibrary/Core.hlsl"
#elif defined(USE_URP)
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#else
#include "UnityCG.cginc"
#endif
////////////////////////////////////////
// Space functions
//
inline float4 calculateWorldPos(float4 vertex)
{
return mul(unity_ObjectToWorld, vertex);
}
#if defined(USE_LWRP) || defined(USE_URP)
// snaps post-transformed position to screen pixels
inline float4 UnityPixelSnap(float4 pos)
{
float2 hpc = _ScreenParams.xy * 0.5f;
#if SHADER_API_PSSL
// sdk 4.5 splits round into v_floor_f32(x+0.5) ... sdk 5.0 uses v_rndne_f32, for compatabilty we use the 4.5 version
float2 temp = ((pos.xy / pos.w) * hpc) + float2(0.5f, 0.5f);
float2 pixelPos = float2(__v_floor_f32(temp.x), __v_floor_f32(temp.y));
#else
float2 pixelPos = round((pos.xy / pos.w) * hpc);
#endif
pos.xy = pixelPos / hpc * pos.w;
return pos;
}
#endif
inline float4 calculateLocalPos(float4 vertex)
{
#if !defined(USE_LWRP) && !defined(USE_URP)
#ifdef UNITY_INSTANCING_ENABLED
vertex.xy *= _Flip.xy;
#endif
#endif
#if defined(USE_LWRP) || defined(USE_URP)
float4 pos = TransformObjectToHClip(vertex.xyz);
#else
float4 pos = UnityObjectToClipPos(vertex);
#endif
#ifdef PIXELSNAP_ON
pos = UnityPixelSnap(pos);
#endif
return pos;
}
inline half3 calculateWorldNormal(float3 normal)
{
#if defined(USE_LWRP) || defined(USE_URP)
return TransformObjectToWorldNormal(normal);
#else
return UnityObjectToWorldNormal(normal);
#endif
}
////////////////////////////////////////
// Normal map functions
//
#if defined(_NORMALMAP)
uniform sampler2D _BumpMap;
#if !defined(USE_LWRP) && !defined(USE_URP)
uniform half _BumpScale;
#endif
half3 UnpackScaleNormal(half4 packednormal, half bumpScale)
{
#if defined(UNITY_NO_DXT5nm)
return packednormal.xyz * 2 - 1;
#else
half3 normal;
normal.xy = (packednormal.wy * 2 - 1);
// Note: we allow scaled normals in LWRP since we might be using fewer instructions.
#if (SHADER_TARGET >= 30) || defined(USE_LWRP) || defined(USE_URP)
// SM2.0: instruction count limitation
// SM2.0: normal scaler is not supported
normal.xy *= bumpScale;
#endif
normal.z = sqrt(1.0 - saturate(dot(normal.xy, normal.xy)));
return normal;
#endif
}
inline half3 calculateWorldTangent(float4 tangent)
{
#if defined(USE_LWRP) || defined(USE_URP)
return TransformObjectToWorldDir(tangent.xyz);
#else
return UnityObjectToWorldDir(tangent);
#endif
}
inline half3 calculateWorldBinormal(half3 normalWorld, half3 tangentWorld, float tangentSign)
{
//When calculating the binormal we have to flip it when the mesh is scaled negatively.
//Normally this would just be unity_WorldTransformParams.w but this isn't set correctly by Unity for its SpriteRenderer meshes so get from objectToWorld matrix scale instead.
half worldTransformSign = sign(unity_ObjectToWorld[0][0] * unity_ObjectToWorld[1][1] * unity_ObjectToWorld[2][2]);
half sign = tangentSign * worldTransformSign;
return cross(normalWorld, tangentWorld) * sign;
}
inline half3 calculateNormalFromBumpMap(float2 texUV, half3 tangentWorld, half3 binormalWorld, half3 normalWorld)
{
half3 localNormal = UnpackScaleNormal(tex2D(_BumpMap, texUV), _BumpScale);
half3x3 rotation = half3x3(tangentWorld, binormalWorld, normalWorld);
half3 normal = normalize(mul(localNormal, rotation));
return normal;
}
#endif // _NORMALMAP
////////////////////////////////////////
// Blending functions
//
inline fixed4 prepareLitPixelForOutput(fixed4 finalPixel, fixed4 color) : SV_Target
{
#if defined(_ALPHABLEND_ON)
//Normal Alpha
finalPixel.rgb *= finalPixel.a;
#elif defined(_ALPHAPREMULTIPLY_ON)
//Pre multiplied alpha
finalPixel.rgb *= color.a;
#elif defined(_MULTIPLYBLEND)
//Multiply
finalPixel = lerp(fixed4(1,1,1,1), finalPixel, finalPixel.a);
#elif defined(_MULTIPLYBLEND_X2)
//Multiply x2
finalPixel.rgb *= 2.0f;
finalPixel = lerp(fixed4(0.5f,0.5f,0.5f,0.5f), finalPixel, finalPixel.a);
#elif defined(_ADDITIVEBLEND)
//Additive
finalPixel *= 2.0f;
finalPixel.rgb *= color.a;
#elif defined(_ADDITIVEBLEND_SOFT)
//Additive soft
finalPixel.rgb *= finalPixel.a;
#else
//Opaque
finalPixel.a = 1;
#endif
return finalPixel;
}
inline fixed4 calculateLitPixel(fixed4 texureColor, fixed4 color, fixed3 lighting) : SV_Target
{
fixed4 finalPixel = texureColor * color * fixed4(lighting, 1);
finalPixel = prepareLitPixelForOutput(finalPixel, color);
return finalPixel;
}
inline fixed4 calculateLitPixel(fixed4 texureColor, fixed3 lighting) : SV_Target
{
// note: we let the optimizer work, removed duplicate code.
return calculateLitPixel(texureColor, fixed4(1, 1, 1, 1), lighting);
}
inline fixed4 calculateAdditiveLitPixel(fixed4 texureColor, fixed4 color, fixed3 lighting) : SV_Target
{
fixed4 finalPixel;
#if defined(_ALPHABLEND_ON) || defined(_MULTIPLYBLEND) || defined(_MULTIPLYBLEND_X2) || defined(_ADDITIVEBLEND) || defined(_ADDITIVEBLEND_SOFT)
//Normal Alpha, Additive and Multiply modes
finalPixel.rgb = (texureColor.rgb * lighting * color.rgb) * (texureColor.a * color.a);
finalPixel.a = 1.0;
#elif defined(_ALPHAPREMULTIPLY_ON)
//Pre multiplied alpha
finalPixel.rgb = texureColor.rgb * lighting * color.rgb * color.a;
finalPixel.a = 1.0;
#else
//Opaque
finalPixel.rgb = texureColor.rgb * lighting * color.rgb;
finalPixel.a = 1.0;
#endif
return finalPixel;
}
inline fixed4 calculateAdditiveLitPixel(fixed4 texureColor, fixed3 lighting) : SV_Target
{
fixed4 finalPixel;
#if defined(_ALPHABLEND_ON) || defined(_MULTIPLYBLEND) || defined(_MULTIPLYBLEND_X2) || defined(_ADDITIVEBLEND) || defined(_ADDITIVEBLEND_SOFT)
//Normal Alpha, Additive and Multiply modes
finalPixel.rgb = (texureColor.rgb * lighting) * texureColor.a;
finalPixel.a = 1.0;
#else
//Pre multiplied alpha and Opaque
finalPixel.rgb = texureColor.rgb * lighting;
finalPixel.a = 1.0;
#endif
return finalPixel;
}
inline fixed4 calculatePixel(fixed4 texureColor, fixed4 color) : SV_Target
{
// note: we let the optimizer work, removed duplicate code.
return calculateLitPixel(texureColor, color, fixed3(1, 1, 1));
}
inline fixed4 calculatePixel(fixed4 texureColor) : SV_Target
{
// note: we let the optimizer work, removed duplicate code.
return calculateLitPixel(texureColor, fixed4(1, 1, 1, 1), fixed3(1, 1, 1));
}
////////////////////////////////////////
// Alpha Clipping
//
#if defined(_ALPHA_CLIP)
#if !defined(USE_LWRP) && !defined(USE_URP)
uniform fixed _Cutoff;
#endif
#define ALPHA_CLIP(pixel, color) clip((pixel.a * color.a) - _Cutoff);
#else
#define ALPHA_CLIP(pixel, color)
#endif
////////////////////////////////////////
// Additive Slot blend mode
// return unlit textureColor, alpha clip textureColor.a only
//
#if defined(_ALPHAPREMULTIPLY_ON)
#define RETURN_UNLIT_IF_ADDITIVE_SLOT(textureColor, vertexColor) \
if (vertexColor.a == 0 && (vertexColor.r || vertexColor.g || vertexColor.b)) {\
ALPHA_CLIP(texureColor, fixed4(1, 1, 1, 1))\
return texureColor * vertexColor;\
}
#else
#define RETURN_UNLIT_IF_ADDITIVE_SLOT(textureColor, vertexColor)
#endif
////////////////////////////////////////
// Color functions
//
#if !defined(USE_LWRP) && !defined(USE_URP)
uniform fixed4 _Color;
#endif
inline fixed4 calculateVertexColor(fixed4 color)
{
return color * _Color;
}
#if defined(_COLOR_ADJUST)
#if !defined(USE_LWRP) && !defined(USE_URP)
uniform float _Hue;
uniform float _Saturation;
uniform float _Brightness;
uniform fixed4 _OverlayColor;
#endif
float3 rgb2hsv(float3 c)
{
float4 K = float4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
float4 p = lerp(float4(c.bg, K.wz), float4(c.gb, K.xy), step(c.b, c.g));
float4 q = lerp(float4(p.xyw, c.r), float4(c.r, p.yzx), step(p.x, c.r));
float d = q.x - min(q.w, q.y);
float e = 1.0e-10;
return float3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}
float3 hsv2rgb(float3 c)
{
c = float3(c.x, clamp(c.yz, 0.0, 1.0));
float4 K = float4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
float3 p = abs(frac(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * lerp(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
inline fixed4 adjustColor(fixed4 color)
{
float3 hsv = rgb2hsv(color.rgb);
hsv.x += _Hue;
hsv.y *= _Saturation;
hsv.z *= _Brightness;
color.rgb = hsv2rgb(hsv);
return color;
}
#define COLORISE(pixel) pixel.rgb = lerp(pixel.rgb, _OverlayColor.rgb, _OverlayColor.a * pixel.a);
#define COLORISE_ADDITIVE(pixel) pixel.rgb = ((1.0-_OverlayColor.a) * pixel.rgb);
#else // !_COLOR_ADJUST
#define COLORISE(pixel)
#define COLORISE_ADDITIVE(pixel)
#endif // !_COLOR_ADJUST
////////////////////////////////////////
// Fog
//
#if defined(_FOG) && (defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2))
inline fixed4 applyFog(fixed4 pixel, float fogCoordOrFactorAtLWRP)
{
#if defined(_ADDITIVEBLEND) || defined(_ADDITIVEBLEND_SOFT)
//In additive mode blend from clear to black based on luminance
float luminance = pixel.r * 0.3 + pixel.g * 0.59 + pixel.b * 0.11;
fixed4 fogColor = lerp(fixed4(0,0,0,0), fixed4(0,0,0,1), luminance);
#elif defined(_MULTIPLYBLEND)
//In multiplied mode fade to white based on inverse luminance
float luminance = pixel.r * 0.3 + pixel.g * 0.59 + pixel.b * 0.11;
fixed4 fogColor = lerp(fixed4(1,1,1,1), fixed4(0,0,0,0), luminance);
#elif defined(_MULTIPLYBLEND_X2)
//In multipliedx2 mode fade to grey based on inverse luminance
float luminance = pixel.r * 0.3 + pixel.g * 0.59 + pixel.b * 0.11;
fixed4 fogColor = lerp(fixed4(0.5f,0.5f,0.5f,0.5f), fixed4(0,0,0,0), luminance);
#elif defined(_ALPHABLEND_ON) || defined(_ALPHAPREMULTIPLY_ON)
//In alpha blended modes blend to fog color based on pixel alpha
fixed4 fogColor = lerp(fixed4(0,0,0,0), unity_FogColor, pixel.a);
#else
//In opaque mode just return fog color;
fixed4 fogColor = unity_FogColor;
#endif
#if defined(USE_LWRP) || defined(USE_URP)
pixel.rgb = MixFogColor(pixel.rgb, fogColor.rgb, fogCoordOrFactorAtLWRP);
#else
UNITY_APPLY_FOG_COLOR(fogCoordOrFactorAtLWRP, pixel, fogColor);
#endif
return pixel;
}
#define APPLY_FOG(pixel, input) pixel = applyFog(pixel, input.fogCoord);
#define APPLY_FOG_LWRP(pixel, fogFactor) pixel = applyFog(pixel, fogFactor);
#define APPLY_FOG_ADDITIVE(pixel, input) \
UNITY_APPLY_FOG_COLOR(input.fogCoord, pixel.rgb, fixed4(0,0,0,0)); // fog towards black in additive pass
#else
#define APPLY_FOG(pixel, input)
#define APPLY_FOG_LWRP(pixel, fogFactor)
#define APPLY_FOG_ADDITIVE(pixel, input)
#endif
////////////////////////////////////////
// Texture functions
//
uniform sampler2D _MainTex;
#if _TEXTURE_BLEND
uniform sampler2D _BlendTex;
#if !defined(USE_LWRP) && !defined(USE_URP)
uniform float _BlendAmount;
#endif
inline fixed4 calculateBlendedTexturePixel(float2 texcoord)
{
return (1.0-_BlendAmount) * tex2D(_MainTex, texcoord) + _BlendAmount * tex2D(_BlendTex, texcoord);
}
#endif // _TEXTURE_BLEND
inline fixed4 calculateTexturePixel(float2 texcoord)
{
fixed4 pixel;
#if _TEXTURE_BLEND
pixel = calculateBlendedTexturePixel(texcoord);
#else
pixel = tex2D(_MainTex, texcoord);
#endif // !_TEXTURE_BLEND
#if defined(_COLOR_ADJUST)
pixel = adjustColor(pixel);
#endif // _COLOR_ADJUST
return pixel;
}
#if !defined(USE_LWRP) && !defined(USE_URP)
uniform fixed4 _MainTex_ST;
#endif
inline float2 calculateTextureCoord(float4 texcoord)
{
return TRANSFORM_TEX(texcoord, _MainTex);
}
#endif // SHADER_SHARED_INCLUDED

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: c18c5cab567666f4d8c5b2bd4e61390b
timeCreated: 1494092582
licenseType: Free
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 5d7322e83d799d849bea71dbd6f1c24e
folderAsset: yes
timeCreated: 1563297885
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,35 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: SkeletonPMAAdditive
m_Shader: {fileID: 4800000, guid: 53efa1d97f5d9f74285d4330cda14e36, type: 3}
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- <noninit>:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- <noninit>: 0
- _Cutoff: 0.1
- _StraightAlphaInput: 0
m_Colors:
- <noninit>: {r: 0, g: 2.018574, b: 1e-45, a: 0.000007110106}
- _Color: {r: 1, g: 1, b: 1, a: 1}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 4deba332d47209e4780b3c5fcf0e3745
timeCreated: 1496447909
licenseType: Free
NativeFormatImporter:
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,43 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: SkeletonPMAMultiply
m_Shader: {fileID: 4800000, guid: 8bdcdc7ee298e594a9c20c61d25c33b6, type: 3}
m_ShaderKeywords:
m_LightmapFlags: 4
m_CustomRenderQueue: -1
stringTagMap: {}
m_SavedProperties:
serializedVersion: 2
m_TexEnvs:
- first:
name: <noninit>
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _MainTex
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- first:
name: <noninit>
second: 0
- first:
name: _Cutoff
second: 0.1
m_Colors:
- first:
name: <noninit>
second: {r: 0, g: 2.018574, b: 1e-45, a: 0.000007110106}
- first:
name: _Color
second: {r: 1, g: 1, b: 1, a: 1}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 53bf0ab317d032d418cf1252d68f51df
timeCreated: 1496447909
licenseType: Free
NativeFormatImporter:
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,43 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: SkeletonPMAScreen
m_Shader: {fileID: 4800000, guid: 4e8caa36c07aacf4ab270da00784e4d9, type: 3}
m_ShaderKeywords:
m_LightmapFlags: 4
m_CustomRenderQueue: -1
stringTagMap: {}
m_SavedProperties:
serializedVersion: 2
m_TexEnvs:
- first:
name: <noninit>
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _MainTex
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- first:
name: <noninit>
second: 0
- first:
name: _Cutoff
second: 0.1
m_Colors:
- first:
name: <noninit>
second: {r: 0, g: 2.018574, b: 1e-45, a: 0.000007121922}
- first:
name: _Color
second: {r: 1, g: 1, b: 1, a: 1}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 73f0f46d3177c614baf0fa48d646a9be
timeCreated: 1496447909
licenseType: Free
NativeFormatImporter:
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,614 +0,0 @@
/******************************************************************************
* 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
}
}

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: ea85c8f6a91a6ab45881b0dbdaabb7d0
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -1,168 +0,0 @@
/******************************************************************************
* 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);
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: f4692b9527684d048862210ba3f9834e
timeCreated: 1563321428
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: