forked from EsotericSoftware/spine-runtimes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AssetUtility.cs
1451 lines (1232 loc) · 58.2 KB
/
AssetUtility.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated September 24, 2021. Replaces all prior versions.
*
* Copyright (c) 2013-2021, 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.
*****************************************************************************/
#pragma warning disable 0219
#define SPINE_SKELETONMECANIM
#if UNITY_2017_2_OR_NEWER
#define NEWPLAYMODECALLBACKS
#endif
#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
#define NEW_PREFAB_SYSTEM
#endif
#if UNITY_2018_3_OR_NEWER
#define NEW_PREFERENCES_SETTINGS_PROVIDER
#endif
#if UNITY_2018_2_OR_NEWER
#define EXPOSES_SPRITE_ATLAS_UTILITIES
#endif
#if !UNITY_2019_4_OR_NEWER
#define PROBLEMATIC_PACKAGE_ASSET_MODIFICATION
#endif
#if UNITY_2019_2_OR_NEWER
#define HAS_PACKAGE_INFO
#endif
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEditor;
using UnityEngine;
using CompatibilityProblemInfo = Spine.Unity.SkeletonDataCompatibility.CompatibilityProblemInfo;
namespace Spine.Unity.Editor {
public class PathAndProblemInfo {
public string path;
public CompatibilityProblemInfo compatibilityProblems;
public string otherProblemDescription;
public PathAndProblemInfo (string path, CompatibilityProblemInfo compatibilityInfo, string otherProblemDescription) {
this.path = path;
this.compatibilityProblems = compatibilityInfo;
this.otherProblemDescription = otherProblemDescription;
}
}
public static class AssetUtility {
public const string SkeletonDataSuffix = "_SkeletonData";
public const string AtlasSuffix = "_Atlas";
public const string SpriteAtlasSuffix = "_SpriteAtlas";
/// HACK: This list keeps the asset reference temporarily during importing.
///
/// In cases of very large projects/sufficient RAM pressure, when AssetDatabase.SaveAssets is called,
/// Unity can mistakenly unload assets whose references are only on the stack.
/// This leads to MissingReferenceException and other errors.
public static readonly List<ScriptableObject> protectFromStackGarbageCollection = new List<ScriptableObject>();
public static HashSet<string> assetsImportedInWrongState = new HashSet<string>();
public static void HandleOnPostprocessAllAssets (string[] imported, List<string> texturesWithoutMetaFile) {
// In case user used "Assets -> Reimport All", during the import process,
// asset database is not initialized until some point. During that period,
// all attempts to load any assets using API (i.e. AssetDatabase.LoadAssetAtPath)
// will return null, and as result, assets won't be loaded even if they actually exists,
// which may lead to numerous importing errors.
// This situation also happens if Library folder is deleted from the project, which is a pretty
// common case, since when using version control systems, the Library folder must be excluded.
//
// So to avoid this, in case asset database is not available, we delay loading the assets
// until next time.
//
// Unity *always* reimports some internal assets after the process is done, so this method
// is always called once again in a state when asset database is available.
//
// Checking whether AssetDatabase is initialized is done by attempting to load
// a known "marker" asset that should always be available. Failing to load this asset
// means that AssetDatabase is not initialized.
AssetUtility.assetsImportedInWrongState.UnionWith(imported);
if (AssetDatabaseAvailabilityDetector.IsAssetDatabaseAvailable()) {
string[] combinedAssets = AssetUtility.assetsImportedInWrongState.ToArray();
AssetUtility.assetsImportedInWrongState.Clear();
AssetUtility.ImportSpineContent(combinedAssets, texturesWithoutMetaFile);
}
}
public static bool AssetCanBeModified (string assetPath) {
#if HAS_PACKAGE_INFO
UnityEditor.PackageManager.PackageInfo packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(assetPath);
return (packageInfo == null ||
packageInfo.source == UnityEditor.PackageManager.PackageSource.Embedded ||
packageInfo.source == UnityEditor.PackageManager.PackageSource.Local);
#else
return assetPath.StartsWith("Assets");
#endif
}
#region Match SkeletonData with Atlases
static readonly AttachmentType[] AtlasTypes = { AttachmentType.Region, AttachmentType.Linkedmesh, AttachmentType.Mesh };
public static List<string> GetRequiredAtlasRegions (string skeletonDataPath) {
HashSet<string> requiredPaths = new HashSet<string>();
if (skeletonDataPath.Contains(".skel")) {
List<string> requiredPathsResult = new List<string>();
AddRequiredAtlasRegionsFromBinary(skeletonDataPath, requiredPathsResult);
return requiredPathsResult;
}
TextReader reader = null;
TextAsset spineJson = AssetDatabase.LoadAssetAtPath<TextAsset>(skeletonDataPath);
Dictionary<string, object> root = null;
try {
if (spineJson != null) {
reader = new StringReader(spineJson.text);
} else {
// On a "Reimport All" the order of imports can be wrong, thus LoadAssetAtPath() above could return null.
// as a workaround, we provide a fallback reader.
reader = new StreamReader(skeletonDataPath);
}
root = Json.Deserialize(reader) as Dictionary<string, object>;
} finally {
if (reader != null)
reader.Dispose();
}
if (root == null || !root.ContainsKey("skins"))
return new List<string>();
List<object> skinsList = root["skins"] as List<object>;
if (skinsList == null)
return new List<string>();
foreach (Dictionary<string, object> skinMap in skinsList) {
if (!skinMap.ContainsKey("attachments"))
continue;
foreach (var slot in (Dictionary<string, object>)skinMap["attachments"]) {
foreach (var attachment in ((Dictionary<string, object>)slot.Value)) {
var data = ((Dictionary<string, object>)attachment.Value);
// Ignore non-atlas-requiring types.
if (data.ContainsKey("type")) {
AttachmentType attachmentType;
string typeString = (string)data["type"];
try {
attachmentType = (AttachmentType)System.Enum.Parse(typeof(AttachmentType), typeString, true);
} catch (System.ArgumentException e) {
// For more info, visit: http://esotericsoftware.com/forum/Spine-editor-and-runtime-version-management-6534
Debug.LogWarning(string.Format("Unidentified Attachment type: \"{0}\". Skeleton may have been exported from an incompatible Spine version.", typeString), spineJson);
throw e;
}
if (!AtlasTypes.Contains(attachmentType))
continue;
}
if (data.ContainsKey("path"))
requiredPaths.Add((string)data["path"]);
else if (data.ContainsKey("name"))
requiredPaths.Add((string)data["name"]);
else if (data.ContainsKey("sequence")) {
Sequence sequence = SkeletonJson.ReadSequence(data["sequence"]);
if (sequence != null)
for (int index = 0; index < sequence.Regions.Length; ++index)
requiredPaths.Add(sequence.GetPath(attachment.Key, index));
else
requiredPaths.Add(attachment.Key);
} else
requiredPaths.Add(attachment.Key);
}
}
}
return requiredPaths.ToList();
}
internal static void AddRequiredAtlasRegionsFromBinary (string skeletonDataPath, List<string> requiredPaths) {
SkeletonBinary binary = new SkeletonBinary(new AtlasRequirementLoader(requiredPaths));
Stream input = null;
TextAsset data = AssetDatabase.LoadAssetAtPath<TextAsset>(skeletonDataPath);
try {
if (data != null) {
input = new MemoryStream(data.bytes);
} else {
// On a "Reimport All" the order of imports can be wrong, thus LoadAssetAtPath() above could return null.
// as a workaround, we provide a fallback reader.
input = File.Open(skeletonDataPath, FileMode.Open, FileAccess.Read);
}
binary.ReadSkeletonData(input);
} finally {
if (input != null)
input.Dispose();
}
binary = null;
}
internal static AtlasAssetBase GetMatchingAtlas (List<string> requiredPaths, string skeletonName,
List<AtlasAssetBase> atlasAssets) {
atlasAssets.Sort((a, b) => (
string.CompareOrdinal(b.name, skeletonName)
- string.CompareOrdinal(a.name, skeletonName)));
return GetMatchingAtlas(requiredPaths, atlasAssets);
}
internal static AtlasRegion FindRegionIgnoringNumberSuffix (this Atlas atlas, string regionPath) {
AtlasRegion region = atlas.FindRegion(regionPath);
if (region != null)
return region;
return atlas.FindRegionWithNumberSuffix(regionPath);
}
internal static AtlasRegion FindRegionWithNumberSuffix (this Atlas atlas, string regionPath) {
int pathLength = regionPath.Length;
foreach (AtlasRegion region in atlas.Regions) {
string name = region.name;
if (name.StartsWith(regionPath)) {
string suffix = name.Substring(pathLength);
if (suffix.All(c => c >= '0' && c <= '9'))
return region;
}
}
return null;
}
internal static AtlasAssetBase GetMatchingAtlas (List<string> requiredPaths, List<AtlasAssetBase> atlasAssets) {
AtlasAssetBase atlasAssetMatch = null;
foreach (AtlasAssetBase a in atlasAssets) {
Atlas atlas = a.GetAtlas();
bool failed = false;
foreach (string regionPath in requiredPaths) {
if (atlas.FindRegionIgnoringNumberSuffix(regionPath) == null) {
failed = true;
break;
}
}
if (!failed) {
atlasAssetMatch = a;
break;
}
}
return atlasAssetMatch;
}
public class AtlasRequirementLoader : AttachmentLoader {
List<string> requirementList;
public AtlasRequirementLoader (List<string> requirementList) {
this.requirementList = requirementList;
}
public RegionAttachment NewRegionAttachment (Skin skin, string name, string path, Sequence sequence) {
RegionAttachment regionAttachment = new RegionAttachment(name);
if (sequence != null)
LoadSequence(path, sequence);
else {
requirementList.Add(path);
AssignDummyRegion(regionAttachment);
}
return regionAttachment;
}
public MeshAttachment NewMeshAttachment (Skin skin, string name, string path, Sequence sequence) {
MeshAttachment meshAttachment = new MeshAttachment(name);
if (sequence != null)
LoadSequence(path, sequence);
else {
requirementList.Add(path);
AssignDummyRegion(meshAttachment);
}
return meshAttachment;
}
public BoundingBoxAttachment NewBoundingBoxAttachment (Skin skin, string name) {
return new BoundingBoxAttachment(name);
}
public PathAttachment NewPathAttachment (Skin skin, string name) {
return new PathAttachment(name);
}
public PointAttachment NewPointAttachment (Skin skin, string name) {
return new PointAttachment(name);
}
public ClippingAttachment NewClippingAttachment (Skin skin, string name) {
return new ClippingAttachment(name);
}
private void LoadSequence (string basePath, Sequence sequence) {
TextureRegion[] regions = sequence.Regions;
for (int i = 0, n = regions.Length; i < n; i++) {
string path = sequence.GetPath(basePath, i);
requirementList.Add(path);
}
}
private static void AssignDummyRegion (IHasTextureRegion attachment) {
attachment.Region = new AtlasRegion();
}
}
#endregion
public static void ImportSpineContent (string[] imported, List<string> texturesWithoutMetaFile,
bool reimport = false) {
List<string> atlasPaths = new List<string>();
List<string> imagePaths = new List<string>();
List<PathAndProblemInfo> skeletonPaths = new List<PathAndProblemInfo>();
CompatibilityProblemInfo compatibilityProblemInfo = null;
foreach (string str in imported) {
string extension = Path.GetExtension(str).ToLower();
switch (extension) {
case ".atlas":
if (SpineEditorUtilities.Preferences.atlasTxtImportWarning) {
Debug.LogWarningFormat("`{0}` : If this file is a Spine atlas, please change its extension to `.atlas.txt`. This is to allow Unity to recognize it and avoid filename collisions. You can also set this file extension when exporting from the Spine editor.", str);
}
break;
case ".skel":
if (SpineEditorUtilities.Preferences.atlasTxtImportWarning) {
Debug.LogWarningFormat("`{0}` : If this file is a Spine skeleton, please change its extension to `.skel.bytes`. This is to allow Unity to recognize it and avoid filename collisions. You can also set this file extension when exporting from the Spine editor.", str);
}
break;
case ".txt":
if (str.EndsWith(".atlas.txt", System.StringComparison.Ordinal))
atlasPaths.Add(str);
break;
case ".png":
case ".jpg":
imagePaths.Add(str);
break;
case ".json": {
TextAsset jsonAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(str);
string problemDescription = null;
if (jsonAsset != null && IsSpineData(jsonAsset, out compatibilityProblemInfo, ref problemDescription))
skeletonPaths.Add(new PathAndProblemInfo(str, compatibilityProblemInfo, problemDescription));
if (problemDescription != null)
Debug.LogError(problemDescription, jsonAsset);
break;
}
case ".bytes": {
if (str.ToLower().EndsWith(".skel.bytes", System.StringComparison.Ordinal)) {
TextAsset binaryAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(str);
string problemDescription = null;
if (IsSpineData(binaryAsset, out compatibilityProblemInfo, ref problemDescription))
skeletonPaths.Add(new PathAndProblemInfo(str, compatibilityProblemInfo, problemDescription));
if (problemDescription != null)
Debug.LogError(problemDescription, binaryAsset);
}
break;
}
}
}
AddDependentAtlasIfImageChanged(atlasPaths, imagePaths);
// Import atlases first.
List<AtlasAssetBase> newAtlases = new List<AtlasAssetBase>();
foreach (string ap in atlasPaths) {
#if PROBLEMATIC_PACKAGE_ASSET_MODIFICATION
if (ap.StartsWith("Packages"))
continue;
#endif
TextAsset atlasText = AssetDatabase.LoadAssetAtPath<TextAsset>(ap);
AtlasAssetBase atlas = IngestSpineAtlas(atlasText, texturesWithoutMetaFile);
newAtlases.Add(atlas);
}
AddDependentSkeletonIfAtlasChanged(skeletonPaths, atlasPaths);
// Import skeletons and match them with atlases.
bool abortSkeletonImport = false;
foreach (PathAndProblemInfo skeletonPathEntry in skeletonPaths) {
string skeletonPath = skeletonPathEntry.path;
CompatibilityProblemInfo compatibilityProblems = skeletonPathEntry.compatibilityProblems;
string otherProblemDescription = skeletonPathEntry.otherProblemDescription;
#if PROBLEMATIC_PACKAGE_ASSET_MODIFICATION
if (skeletonPath.StartsWith("Packages"))
continue;
#endif
if (!reimport && CheckForValidSkeletonData(skeletonPath)) {
ReloadSkeletonData(skeletonPath, compatibilityProblems);
continue;
}
TextAsset loadedAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(skeletonPath);
if (compatibilityProblems != null) {
IngestIncompatibleSpineProject(loadedAsset, compatibilityProblems);
continue;
}
if (otherProblemDescription != null) {
continue;
}
string dir = Path.GetDirectoryName(skeletonPath).Replace('\\', '/');
#if SPINE_TK2D
IngestSpineProject(loadedAsset, null);
#else
string skeletonName = Path.GetFileNameWithoutExtension(skeletonPath);
List<string> requiredPaths = GetRequiredAtlasRegions(skeletonPath);
List<AtlasAssetBase> atlasesForSkeleton = FindAtlasesAtPath(dir);
atlasesForSkeleton = atlasesForSkeleton.Union(newAtlases).ToList();
List<AtlasAssetBase> atlasesInSameDir = atlasesForSkeleton.Where(
atlas => AssetDatabase.GetAssetPath(atlas).Contains(dir)).ToList();
AtlasAssetBase atlasMatch = GetMatchingAtlas(requiredPaths, skeletonName, atlasesInSameDir);
if (atlasMatch == null && atlasesInSameDir.Count > 0) {
AtlasAssetBase firstAtlas = atlasesInSameDir[0];
Debug.LogWarning(string.Format(
"'{0}' atlas found in skeleton directory does not contain all required attachments",
firstAtlas.name), firstAtlas);
List<AtlasAssetBase> atlasesInOtherDir = atlasesForSkeleton.Except(atlasesInSameDir).ToList();
atlasMatch = GetMatchingAtlas(requiredPaths, skeletonName, atlasesInOtherDir);
if (atlasMatch != null) {
Debug.Log(string.Format(
"Using suitable atlas '{0}' of other imported directory. If this is the " +
"wrong atlas asset, please assign the correct one at the SkeletonData asset.",
atlasMatch.name), atlasMatch);
}
}
if (atlasMatch != null || requiredPaths.Count == 0) {
IngestSpineProject(loadedAsset, atlasMatch);
} else {
SkeletonImportDialog(skeletonPath, atlasesForSkeleton, requiredPaths, ref abortSkeletonImport);
}
if (abortSkeletonImport)
break;
#endif
}
if (atlasPaths.Count > 0 || imagePaths.Count > 0 || skeletonPaths.Count > 0) {
SkeletonDataAssetInspector[] skeletonDataInspectors = Resources.FindObjectsOfTypeAll<SkeletonDataAssetInspector>();
foreach (SkeletonDataAssetInspector inspector in skeletonDataInspectors) {
inspector.UpdateSkeletonData();
}
}
// Any post processing of images
// Under some circumstances (e.g. on first import) SkeletonGraphic objects
// have their skeletonGraphic.skeletonDataAsset reference corrupted
// by the instance of the ScriptableObject being destroyed but still assigned.
// Here we restore broken skeletonGraphic.skeletonDataAsset references.
SkeletonGraphic[] skeletonGraphicObjects = Resources.FindObjectsOfTypeAll(typeof(SkeletonGraphic)) as SkeletonGraphic[];
foreach (SkeletonGraphic skeletonGraphic in skeletonGraphicObjects) {
if (skeletonGraphic.skeletonDataAsset == null) {
int skeletonGraphicID = skeletonGraphic.GetInstanceID();
if (SpineEditorUtilities.DataReloadHandler.savedSkeletonDataAssetAtSKeletonGraphicID.ContainsKey(skeletonGraphicID)) {
string assetPath = SpineEditorUtilities.DataReloadHandler.savedSkeletonDataAssetAtSKeletonGraphicID[skeletonGraphicID];
skeletonGraphic.skeletonDataAsset = (SkeletonDataAsset)AssetDatabase.LoadAssetAtPath<SkeletonDataAsset>(assetPath);
}
}
}
}
static void AddDependentAtlasIfImageChanged (List<string> atlasPaths, List<string> imagePaths) {
foreach (string imagePath in imagePaths) {
string atlasPath = Path.ChangeExtension(imagePath, ".atlas.txt");
if (!System.IO.File.Exists(atlasPath))
continue;
if (!atlasPaths.Contains(atlasPath)) {
atlasPaths.Add(atlasPath);
}
}
}
static void AddDependentSkeletonIfAtlasChanged (List<PathAndProblemInfo> skeletonPaths, List<string> atlasPaths) {
foreach (string atlasPath in atlasPaths) {
string skeletonPathJson = atlasPath.Replace(".atlas.txt", ".json");
string skeletonPathBinary = atlasPath.Replace(".atlas.txt", ".skel.bytes");
string usedSkeletonPath = System.IO.File.Exists(skeletonPathJson) ? skeletonPathJson :
System.IO.File.Exists(skeletonPathBinary) ? skeletonPathBinary : null;
if (usedSkeletonPath == null)
continue;
if (skeletonPaths.FindIndex(p => { return p.path == usedSkeletonPath; }) < 0) {
string problemDescription = null;
CompatibilityProblemInfo compatibilityProblemInfo = null;
TextAsset textAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(usedSkeletonPath);
if (textAsset != null && IsSpineData(textAsset, out compatibilityProblemInfo, ref problemDescription))
skeletonPaths.Add(new PathAndProblemInfo(usedSkeletonPath, compatibilityProblemInfo, problemDescription));
}
}
}
static void ReloadSkeletonData (string skeletonJSONPath, CompatibilityProblemInfo compatibilityProblemInfo) {
string dir = Path.GetDirectoryName(skeletonJSONPath).Replace('\\', '/');
TextAsset textAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(skeletonJSONPath);
DirectoryInfo dirInfo = new DirectoryInfo(dir);
FileInfo[] files = dirInfo.GetFiles("*.asset");
foreach (FileInfo f in files) {
string localPath = dir + "/" + f.Name;
UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath(localPath, typeof(Object));
SkeletonDataAsset skeletonDataAsset = obj as SkeletonDataAsset;
if (skeletonDataAsset != null) {
if (skeletonDataAsset.skeletonJSON == textAsset) {
if (Selection.activeObject == skeletonDataAsset)
Selection.activeObject = null;
if (compatibilityProblemInfo != null) {
SkeletonDataCompatibility.DisplayCompatibilityProblem(compatibilityProblemInfo.DescriptionString(), textAsset);
return;
}
Debug.LogFormat("Changes to '{0}' or atlas detected. Clearing SkeletonDataAsset: {1}", skeletonJSONPath, localPath);
SpineEditorUtilities.ClearSkeletonDataAsset(skeletonDataAsset);
string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(skeletonDataAsset));
string lastHash = EditorPrefs.GetString(guid + "_hash");
// For some weird reason sometimes Unity loses the internal Object pointer,
// and as a result, all comparisons with null returns true.
// But the C# wrapper is still alive, so we can "restore" the object
// by reloading it from its Instance ID.
AtlasAssetBase[] skeletonDataAtlasAssets = skeletonDataAsset.atlasAssets;
if (skeletonDataAtlasAssets != null) {
for (int i = 0; i < skeletonDataAtlasAssets.Length; i++) {
if (!ReferenceEquals(null, skeletonDataAtlasAssets[i]) &&
skeletonDataAtlasAssets[i].Equals(null) &&
skeletonDataAtlasAssets[i].GetInstanceID() != 0
) {
skeletonDataAtlasAssets[i] = EditorUtility.InstanceIDToObject(skeletonDataAtlasAssets[i].GetInstanceID()) as AtlasAssetBase;
}
}
}
SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(true);
if (skeletonData != null)
BlendModeMaterialsUtility.UpdateBlendModeMaterials(skeletonDataAsset, ref skeletonData);
string currentHash = skeletonData != null ? skeletonData.Hash : null;
#if SPINE_SKELETONMECANIM
if (currentHash == null || lastHash != currentHash)
SkeletonBaker.UpdateMecanimClips(skeletonDataAsset);
#endif
// if (currentHash == null || lastHash != currentHash)
// Do any upkeep on synchronized assets
if (currentHash != null)
EditorPrefs.SetString(guid + "_hash", currentHash);
}
SpineEditorUtilities.DataReloadHandler.ReloadSceneSkeletonComponents(skeletonDataAsset);
SpineEditorUtilities.DataReloadHandler.ReloadAnimationReferenceAssets(skeletonDataAsset);
}
}
}
#region Import Atlases
static List<AtlasAssetBase> FindAtlasesAtPath (string path) {
List<AtlasAssetBase> arr = new List<AtlasAssetBase>();
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] assetInfoArr = dir.GetFiles("*.asset");
int subLen = Application.dataPath.Length - 6;
foreach (FileInfo f in assetInfoArr) {
string assetRelativePath = f.FullName.Substring(subLen, f.FullName.Length - subLen).Replace("\\", "/");
Object obj = AssetDatabase.LoadAssetAtPath(assetRelativePath, typeof(AtlasAssetBase));
if (obj != null)
arr.Add(obj as AtlasAssetBase);
}
return arr;
}
static AtlasAssetBase IngestSpineAtlas (TextAsset atlasText, List<string> texturesWithoutMetaFile) {
if (atlasText == null) {
Debug.LogWarning("Atlas source cannot be null!");
return null;
}
string primaryName = Path.GetFileNameWithoutExtension(atlasText.name).Replace(".atlas", "");
string assetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(atlasText)).Replace('\\', '/');
string atlasPath = assetPath + "/" + primaryName + AtlasSuffix + ".asset";
SpineAtlasAsset atlasAsset = (SpineAtlasAsset)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(SpineAtlasAsset));
List<Material> vestigialMaterials = new List<Material>();
if (atlasAsset == null)
atlasAsset = SpineAtlasAsset.CreateInstance<SpineAtlasAsset>();
else {
foreach (Material m in atlasAsset.materials)
vestigialMaterials.Add(m);
}
protectFromStackGarbageCollection.Add(atlasAsset);
atlasAsset.atlasFile = atlasText;
List<string> pageFiles = new List<string>();
atlasAsset.Clear(); // force reload
Atlas atlas = atlasAsset.GetAtlas(onlyMetaData: true);
if (atlas != null) {
foreach (AtlasPage page in atlas.Pages)
pageFiles.Add(page.name);
}
List<Material> populatingMaterials = new List<Material>(pageFiles.Count);
for (int i = 0; i < pageFiles.Count; i++) {
string texturePath = assetPath + "/" + pageFiles[i];
Texture2D texture = (Texture2D)AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D));
bool textureIsUninitialized = texturesWithoutMetaFile != null && texturesWithoutMetaFile.Contains(texturePath);
if (SpineEditorUtilities.Preferences.setTextureImporterSettings && textureIsUninitialized) {
if (string.IsNullOrEmpty(SpineEditorUtilities.Preferences.textureSettingsReference))
SetDefaultTextureSettings(texturePath, atlasAsset);
else
SetReferenceTextureSettings(texturePath, atlasAsset, SpineEditorUtilities.Preferences.textureSettingsReference);
}
string pageName = Path.GetFileNameWithoutExtension(pageFiles[i]);
//because this looks silly
if (pageName == primaryName && pageFiles.Count == 1)
pageName = "Material";
string materialPath = assetPath + "/" + primaryName + "_" + pageName + ".mat";
Material material = (Material)AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material));
if (material == null) {
Shader defaultShader = GetDefaultShader();
material = defaultShader != null ? new Material(defaultShader) : null;
if (material) {
ApplyPMAOrStraightAlphaSettings(material, SpineEditorUtilities.Preferences.textureSettingsReference);
if (texture != null)
material.mainTexture = texture;
AssetDatabase.CreateAsset(material, materialPath);
}
} else {
vestigialMaterials.Remove(material);
if (texture != null)
material.mainTexture = texture;
EditorUtility.SetDirty(material);
// note: don't call AssetDatabase.SaveAssets() since this would trigger OnPostprocessAllAssets() every time unnecessarily.
}
if (material != null) {
populatingMaterials.Add(material);
}
}
atlasAsset.materials = populatingMaterials.ToArray();
for (int i = 0; i < vestigialMaterials.Count; i++)
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(vestigialMaterials[i]));
if (AssetDatabase.GetAssetPath(atlasAsset) == "")
AssetDatabase.CreateAsset(atlasAsset, atlasPath);
else
atlasAsset.Clear();
EditorUtility.SetDirty(atlasAsset);
AssetDatabase.SaveAssets();
if (pageFiles.Count != atlasAsset.materials.Length)
Debug.LogWarning(string.Format("{0} :: Not all atlas pages were imported. If you rename your image files, please make sure you also edit the filenames specified in the atlas file.", atlasAsset.name), atlasAsset);
else
Debug.Log(string.Format("{0} :: Imported with {1} material", atlasAsset.name, atlasAsset.materials.Length), atlasAsset);
// Iterate regions and bake marked.
atlasAsset.Clear();
atlas = atlasAsset.GetAtlas(onlyMetaData: false);
if (atlas != null) {
FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.NonPublic);
List<AtlasRegion> regions = (List<AtlasRegion>)field.GetValue(atlas);
string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset);
string atlasAssetDirPath = Path.GetDirectoryName(atlasAssetPath).Replace('\\', '/');
string bakedDirPath = Path.Combine(atlasAssetDirPath, atlasAsset.name);
bool hasBakedRegions = false;
for (int i = 0; i < regions.Count; i++) {
AtlasRegion region = regions[i];
string bakedPrefabPath = Path.Combine(bakedDirPath, AssetUtility.GetPathSafeName(region.name) + ".prefab").Replace("\\", "/");
GameObject prefab = (GameObject)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(GameObject));
if (prefab != null) {
SkeletonBaker.BakeRegion(atlasAsset, region, false);
hasBakedRegions = true;
}
}
if (hasBakedRegions) {
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
}
protectFromStackGarbageCollection.Remove(atlasAsset);
// note: at Asset Pipeline V2 this LoadAssetAtPath of the just created
// asset returns null, regardless of refresh calls.
AtlasAssetBase loadedAtlas = (AtlasAssetBase)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(AtlasAssetBase));
return loadedAtlas != null ? loadedAtlas : atlasAsset;
}
public static Shader GetDefaultShader () {
Shader shader = Shader.Find(SpineEditorUtilities.Preferences.DefaultShader);
if (shader == null) shader = Shader.Find("Spine/Skeleton");
if (shader == null) shader = Shader.Find("Standard");
return shader;
}
public static bool SpriteAtlasSettingsNeedAdjustment (UnityEngine.U2D.SpriteAtlas spriteAtlas) {
#if EXPOSES_SPRITE_ATLAS_UTILITIES
UnityEditor.U2D.SpriteAtlasPackingSettings packingSettings = UnityEditor.U2D.SpriteAtlasExtensions.GetPackingSettings(spriteAtlas);
UnityEditor.U2D.SpriteAtlasTextureSettings textureSettings = UnityEditor.U2D.SpriteAtlasExtensions.GetTextureSettings(spriteAtlas);
bool areSettingsAsDesired =
packingSettings.enableRotation == true &&
packingSettings.enableTightPacking == false &&
textureSettings.readable == true &&
textureSettings.generateMipMaps == false;
// note: platformSettings.textureCompression is always providing "Compressed", so we have to skip it.
return !areSettingsAsDesired;
#else
return false;
#endif
}
public static bool AdjustSpriteAtlasSettings (UnityEngine.U2D.SpriteAtlas spriteAtlas) {
#if EXPOSES_SPRITE_ATLAS_UTILITIES
UnityEditor.U2D.SpriteAtlasPackingSettings packingSettings = UnityEditor.U2D.SpriteAtlasExtensions.GetPackingSettings(spriteAtlas);
UnityEditor.U2D.SpriteAtlasTextureSettings textureSettings = UnityEditor.U2D.SpriteAtlasExtensions.GetTextureSettings(spriteAtlas);
packingSettings.enableRotation = true;
packingSettings.enableTightPacking = false;
UnityEditor.U2D.SpriteAtlasExtensions.SetPackingSettings(spriteAtlas, packingSettings);
textureSettings.readable = true;
textureSettings.generateMipMaps = false;
UnityEditor.U2D.SpriteAtlasExtensions.SetTextureSettings(spriteAtlas, textureSettings);
TextureImporterPlatformSettings platformSettings = new TextureImporterPlatformSettings();
platformSettings.textureCompression = TextureImporterCompression.Uncompressed;
platformSettings.crunchedCompression = false;
UnityEditor.U2D.SpriteAtlasExtensions.SetPlatformSettings(spriteAtlas, platformSettings);
string atlasPath = AssetDatabase.GetAssetPath(spriteAtlas);
Debug.Log(string.Format("Adjusted unsuitable SpriteAtlas settings '{0}'", atlasPath), spriteAtlas);
return false;
#else
return true;
#endif
}
public static bool GeneratePngFromSpriteAtlas (UnityEngine.U2D.SpriteAtlas spriteAtlas, out string texturePath) {
texturePath = System.IO.Path.ChangeExtension(AssetDatabase.GetAssetPath(spriteAtlas), ".png");
if (spriteAtlas == null)
return false;
Texture2D tempTexture = SpineSpriteAtlasAsset.AccessPackedTextureEditor(spriteAtlas);
if (tempTexture == null)
return false;
byte[] bytes = null;
try {
bytes = tempTexture.EncodeToPNG();
} catch (System.Exception) {
// handled below
}
if (bytes == null || bytes.Length == 0) {
Debug.LogError("Could not read Compressed SpriteAtlas. Please enable 'Read/Write Enabled' and ensure 'Compression' is set to 'None' in Inspector.", spriteAtlas);
return false;
}
System.IO.File.WriteAllBytes(texturePath, bytes);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
return System.IO.File.Exists(texturePath);
}
public static AtlasAssetBase IngestSpriteAtlas (UnityEngine.U2D.SpriteAtlas spriteAtlas, List<string> texturesWithoutMetaFile) {
if (spriteAtlas == null) {
Debug.LogWarning("SpriteAtlas source cannot be null!");
return null;
}
if (SpriteAtlasSettingsNeedAdjustment(spriteAtlas)) {
// settings need to be adjusted via the 'Spine SpriteAtlas Import' window if you want to use it as a Spine atlas.
return null;
}
Texture2D texture = null;
{ // only one page file
string texturePath;
GeneratePngFromSpriteAtlas(spriteAtlas, out texturePath);
texture = AssetDatabase.LoadAssetAtPath<Texture2D>(texturePath);
if (texture == null && System.IO.File.Exists(texturePath)) {
EditorUtility.SetDirty(spriteAtlas);
return null; // next iteration will load the texture as well.
}
}
string primaryName = spriteAtlas.name;
string assetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(spriteAtlas)).Replace('\\', '/');
string atlasPath = assetPath + "/" + primaryName + SpriteAtlasSuffix + ".asset";
SpineSpriteAtlasAsset atlasAsset = AssetDatabase.LoadAssetAtPath<SpineSpriteAtlasAsset>(atlasPath);
List<Material> vestigialMaterials = new List<Material>();
if (atlasAsset == null)
atlasAsset = SpineSpriteAtlasAsset.CreateInstance<SpineSpriteAtlasAsset>();
else {
foreach (Material m in atlasAsset.materials)
vestigialMaterials.Add(m);
}
protectFromStackGarbageCollection.Add(atlasAsset);
atlasAsset.spriteAtlasFile = spriteAtlas;
int pagesCount = 1;
List<Material> populatingMaterials = new List<Material>(pagesCount);
{
string pageName = "SpriteAtlas";
string materialPath = assetPath + "/" + primaryName + "_" + pageName + ".mat";
Material material = AssetDatabase.LoadAssetAtPath<Material>(materialPath);
if (material == null) {
Shader defaultShader = GetDefaultShader();
material = defaultShader != null ? new Material(defaultShader) : null;
ApplyPMAOrStraightAlphaSettings(material, SpineEditorUtilities.Preferences.textureSettingsReference);
AssetDatabase.CreateAsset(material, materialPath);
} else {
vestigialMaterials.Remove(material);
}
if (texture != null)
material.mainTexture = texture;
EditorUtility.SetDirty(material);
// note: don't call AssetDatabase.SaveAssets() since this would trigger OnPostprocessAllAssets() every time unnecessarily.
populatingMaterials.Add(material);
}
atlasAsset.materials = populatingMaterials.ToArray();
for (int i = 0; i < vestigialMaterials.Count; i++)
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(vestigialMaterials[i]));
if (AssetDatabase.GetAssetPath(atlasAsset) == "")
AssetDatabase.CreateAsset(atlasAsset, atlasPath);
else
atlasAsset.Clear();
atlasAsset.GetAtlas();
atlasAsset.updateRegionsInPlayMode = true;
EditorUtility.SetDirty(atlasAsset);
AssetDatabase.SaveAssets();
Debug.Log(string.Format("{0} :: Imported with {1} material", atlasAsset.name, atlasAsset.materials.Length), atlasAsset);
protectFromStackGarbageCollection.Remove(atlasAsset);
return (AtlasAssetBase)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(AtlasAssetBase));
}
static bool SetDefaultTextureSettings (string texturePath, SpineAtlasAsset atlasAsset) {
TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(texturePath);
if (texImporter == null) {
Debug.LogWarning(string.Format("{0}: Texture asset \"{1}\" not found. Skipping. Please check your atlas file for renamed files.", atlasAsset.name, texturePath), atlasAsset);
return false;
}
texImporter.sRGBTexture = false; // as PMA is the default, prevent any border issues that may arise when enabling mipmaps later.
texImporter.textureCompression = TextureImporterCompression.Uncompressed;
texImporter.alphaSource = TextureImporterAlphaSource.FromInput;
texImporter.mipmapEnabled = false;
texImporter.alphaIsTransparency = false; // Prevent the texture importer from applying bleed to the transparent parts for PMA.
texImporter.spriteImportMode = SpriteImportMode.None;
texImporter.maxTextureSize = 2048;
EditorUtility.SetDirty(texImporter);
AssetDatabase.ImportAsset(texturePath);
AssetDatabase.SaveAssets();
return true;
}
#if NEW_PREFERENCES_SETTINGS_PROVIDER
static bool SetReferenceTextureSettings (string texturePath, SpineAtlasAsset atlasAsset, string referenceAssetPath) {
UnityEditor.Presets.Preset texturePreset = AssetDatabase.LoadAssetAtPath<UnityEditor.Presets.Preset>(referenceAssetPath);
bool isTexturePreset = texturePreset != null && texturePreset.GetTargetTypeName() == "TextureImporter";
if (!isTexturePreset)
return SetDefaultTextureSettings(texturePath, atlasAsset);
TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(texturePath);
if (texImporter == null) {
Debug.LogWarning(string.Format("{0}: Texture asset \"{1}\" not found. Skipping. Please check your atlas file for renamed files.", atlasAsset.name, texturePath), atlasAsset);
return false;
}
texturePreset.ApplyTo(texImporter);
AssetDatabase.ImportAsset(texturePath);
AssetDatabase.SaveAssets();
return true;
}
#else
static bool SetReferenceTextureSettings (string texturePath, SpineAtlasAsset atlasAsset, string referenceAssetPath) {
TextureImporter reference = TextureImporter.GetAtPath(referenceAssetPath) as TextureImporter;
if (reference == null)
return SetDefaultTextureSettings(texturePath, atlasAsset);
TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(texturePath);
if (texImporter == null) {
Debug.LogWarning(string.Format("{0}: Texture asset \"{1}\" not found. Skipping. Please check your atlas file for renamed files.", atlasAsset.name, texturePath), atlasAsset);
return false;
}
texImporter.sRGBTexture = reference.sRGBTexture;
texImporter.textureCompression = reference.textureCompression;
texImporter.alphaSource = reference.alphaSource;
texImporter.mipmapEnabled = reference.mipmapEnabled;
texImporter.alphaIsTransparency = reference.alphaIsTransparency;
texImporter.spriteImportMode = reference.spriteImportMode;
texImporter.maxTextureSize = reference.maxTextureSize;
texImporter.isReadable = reference.isReadable;
texImporter.filterMode = reference.filterMode;
texImporter.mipmapFilter = reference.mipmapFilter;
texImporter.textureType = reference.textureType;
EditorUtility.SetDirty(texImporter);
AssetDatabase.ImportAsset(texturePath);
AssetDatabase.SaveAssets();
return true;
}
#endif
static void ApplyPMAOrStraightAlphaSettings (Material material, string referenceTextureSettings) {
bool isUsingPMAWorkflow = string.IsNullOrEmpty(referenceTextureSettings) ||
(!referenceTextureSettings.ToLower().Contains("straight") && referenceTextureSettings.ToLower().Contains("pma"));
MaterialChecks.EnablePMATextureAtMaterial(material, isUsingPMAWorkflow);
}
#endregion
#region Import SkeletonData (json or binary)
internal static string GetSkeletonDataAssetFilePath (TextAsset spineJson) {
string primaryName = Path.GetFileNameWithoutExtension(spineJson.name);
string assetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(spineJson)).Replace('\\', '/');
return assetPath + "/" + primaryName + SkeletonDataSuffix + ".asset";
}
internal static SkeletonDataAsset IngestIncompatibleSpineProject (TextAsset spineJson,
CompatibilityProblemInfo compatibilityProblemInfo) {
if (spineJson == null)
return null;
string filePath = GetSkeletonDataAssetFilePath(spineJson);
SkeletonDataAsset skeletonDataAsset = (SkeletonDataAsset)AssetDatabase.LoadAssetAtPath(filePath, typeof(SkeletonDataAsset));
if (skeletonDataAsset == null) {
skeletonDataAsset = SkeletonDataAsset.CreateInstance<SkeletonDataAsset>();
skeletonDataAsset.skeletonJSON = spineJson;
AssetDatabase.CreateAsset(skeletonDataAsset, filePath);
}