GenericOnDemandTextureLoaderInspector.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated July 28, 2023. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2023, Esoteric Software LLC
  6. *
  7. * Integration of the Spine Runtimes into software or otherwise creating
  8. * derivative works of the Spine Runtimes is permitted under the terms and
  9. * conditions of Section 2 of the Spine Editor License Agreement:
  10. * http://esotericsoftware.com/spine-editor-license
  11. *
  12. * Otherwise, it is permitted to integrate the Spine Runtimes into software or
  13. * otherwise create derivative works of the Spine Runtimes (collectively,
  14. * "Products"), provided that each user of the Products must obtain their own
  15. * Spine Editor license and redistribution of the Products in any form must
  16. * include this license and copyright notice.
  17. *
  18. * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
  24. * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE
  27. * SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. #if UNITY_2017_2_OR_NEWER
  30. #define NEWPLAYMODECALLBACKS
  31. #endif
  32. #define SPINE_OPTIONAL_ON_DEMAND_LOADING
  33. #if SPINE_OPTIONAL_ON_DEMAND_LOADING
  34. using System;
  35. using System.Collections.Generic;
  36. using System.Linq;
  37. using UnityEditor;
  38. using UnityEngine;
  39. namespace Spine.Unity.Editor {
  40. /// <summary>
  41. /// Base class for GenericOnDemandTextureLoader Inspector subclasses.
  42. /// For reference, see the <see cref="AddressablesTextureLoaderInspector"/> class available
  43. /// in the com.esotericsoftware.spine.addressables UPM package.
  44. /// </summary>
  45. /// <typeparam name="TargetReference">The implementation struct which holds an on-demand loading reference
  46. /// to the target texture to be loaded, derived from ITargetTextureReference.</typeparam>
  47. /// <typeparam name="TextureRequest">The implementation struct covering a single texture loading request,
  48. /// derived from IOnDemandRequest</typeparam>
  49. [InitializeOnLoad]
  50. [CustomEditor(typeof(GenericOnDemandTextureLoader<,>)), CanEditMultipleObjects]
  51. public abstract class GenericOnDemandTextureLoaderInspector<TargetReference, TextureRequest> : UnityEditor.Editor
  52. where TargetReference : Spine.Unity.ITargetTextureReference
  53. where TextureRequest : Spine.Unity.IOnDemandRequest {
  54. protected SerializedProperty atlasAsset;
  55. protected SerializedProperty maxPlaceholderSize;
  56. protected SerializedProperty placeholderMap;
  57. protected SerializedProperty unloadAfterSecondsUnused;
  58. static protected bool placeholdersFoldout = true;
  59. protected SerializedProperty loadedDataAtMaterial;
  60. protected GenericOnDemandTextureLoader<TargetReference, TextureRequest> loader;
  61. protected GUIContent placeholderTexturesLabel;
  62. /// <summary>
  63. /// Called via InitializeOnLoad attribute upon Editor startup or compilation.
  64. /// </summary>
  65. static GenericOnDemandTextureLoaderInspector () {
  66. RegisterPlayModeChangedCallbacks();
  67. }
  68. public static void RegisterPlayModeChangedCallbacks () {
  69. #if NEWPLAYMODECALLBACKS
  70. EditorApplication.playModeStateChanged -= OnPlaymodeChanged;
  71. EditorApplication.playModeStateChanged += OnPlaymodeChanged;
  72. #else
  73. EditorApplication.playmodeStateChanged -= OnPlaymodeChanged;
  74. EditorApplication.playmodeStateChanged += OnPlaymodeChanged;
  75. #endif
  76. }
  77. /// <summary>
  78. /// Derive your implementation subclass of this class and implement the respective abstract methods.
  79. /// Note: Unfortunately the Unity menu entries are created via static methods, so this is a workaround
  80. /// to provide virtual static functions in old C# versions.
  81. /// </summary>
  82. public abstract class StaticMethodImplementations {
  83. public abstract GenericOnDemandTextureLoader<TargetReference, TextureRequest> GetOrCreateLoader (string loaderPath);
  84. /// <summary>
  85. /// Returns the on-demand loader asset's filename suffix. The filename
  86. /// is determined by the AtlasAsset, while this suffix replaces the "_Atlas" suffix.
  87. /// When set to e.g. "_Addressable", the loader asset created for
  88. /// the "Skeleton_Atlas" asset is named "Skeleton_Addressable".
  89. /// </summary>
  90. public virtual string LoaderSuffix { get { return "_Loader"; } }
  91. public abstract bool SetupOnDemandLoadingReference (
  92. ref TargetReference targetTextureReference, Texture targetTexture);
  93. /// <summary>
  94. /// Create a context menu wrapper in the main class for this generic implementation using the code below.
  95. /// <code>
  96. /// [MenuItem("CONTEXT/AtlasAssetBase/Add YourSubclass Loader")]
  97. /// static void AddYourSubclassLoader (MenuCommand cmd) {
  98. /// if (staticMethods == null)
  99. /// staticMethods = new YourSubclassMethodImplementations ();
  100. /// staticMethods.AddOnDemandLoader(cmd);
  101. /// }
  102. /// </code>
  103. /// </summary>
  104. public virtual void AddOnDemandLoader (MenuCommand cmd) {
  105. AtlasAssetBase atlasAsset = cmd.context as AtlasAssetBase;
  106. Debug.Log("Adding On-Demand Loader for " + atlasAsset.name, atlasAsset);
  107. if (atlasAsset.OnDemandTextureLoader != null) {
  108. Debug.LogWarning("AtlasAsset On-Demand TextureLoader is already set. " +
  109. "Please clear it if you want to assign a different one.");
  110. return;
  111. }
  112. atlasAsset.TextureLoadingMode = AtlasAssetBase.LoadingMode.OnDemand;
  113. EditorUtility.SetDirty(atlasAsset);
  114. string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset);
  115. string loaderPath = atlasAssetPath.Replace(AssetUtility.AtlasSuffix, LoaderSuffix);
  116. GenericOnDemandTextureLoader<TargetReference, TextureRequest> loader = staticMethods.GetOrCreateLoader(loaderPath);
  117. staticMethods.SetupForAtlasAsset(loader, atlasAsset);
  118. EditorUtility.SetDirty(loader);
  119. AssetDatabase.SaveAssets();
  120. }
  121. public virtual void SetupForAtlasAsset (GenericOnDemandTextureLoader<TargetReference, TextureRequest> loader, AtlasAssetBase atlasAsset) {
  122. if (loader.placeholderMap != null && loader.placeholderMap.Length > 0) {
  123. IEnumerable<Material> modifiedMaterials;
  124. loader.AssignTargetTextures(out modifiedMaterials); // start from normal textures
  125. }
  126. if (atlasAsset == null) {
  127. Debug.LogError("AddressableTextureLoader.SetupForAtlasAsset: atlasAsset was null, aborting setup.", atlasAsset);
  128. return;
  129. }
  130. int materialCount = atlasAsset.MaterialCount;
  131. loader.placeholderMap = new GenericOnDemandTextureLoader<TargetReference, TextureRequest>.PlaceholderMaterialMapping[materialCount];
  132. GenericOnDemandTextureLoader<TargetReference, TextureRequest>.PlaceholderMaterialMapping[] materialMap = loader.placeholderMap;
  133. atlasAsset.OnDemandTextureLoader = loader;
  134. int maxPlaceholderSize = loader.maxPlaceholderSize;
  135. int i = 0;
  136. foreach (Material targetMaterial in atlasAsset.Materials) {
  137. Texture targetTexture = targetMaterial.mainTexture;
  138. materialMap[i].textures = new GenericOnDemandTextureLoader<TargetReference, TextureRequest>.PlaceholderTextureMapping[1]; // Todo: currently only main texture is supported.
  139. int textureIndex = 0;
  140. GenericOnDemandTextureLoader<TargetReference, TextureRequest>.PlaceholderTextureMapping[] texturesMap = materialMap[i].textures;
  141. if (texturesMap[textureIndex].placeholderTexture != targetTexture) { // otherwise already set to placeholder
  142. SetupOnDemandLoadingReference(ref texturesMap[textureIndex].targetTextureReference, targetTexture);
  143. texturesMap[textureIndex].placeholderTexture = CreatePlaceholderTextureFor(targetTexture, maxPlaceholderSize, loader);
  144. }
  145. ++i;
  146. }
  147. // assign late since CreatePlaceholderTextureFor(texture) method above might save assets and clear these values.
  148. loader.placeholderMap = materialMap;
  149. loader.atlasAsset = atlasAsset;
  150. }
  151. public virtual Texture CreatePlaceholderTextureFor (Texture originalTexture, int maxPlaceholderSize,
  152. GenericOnDemandTextureLoader<TargetReference, TextureRequest> loader) {
  153. const string AssetFolderName = "LoadingPlaceholderAssets";
  154. string originalPath = AssetDatabase.GetAssetPath(originalTexture);
  155. string parentFolder = System.IO.Path.GetDirectoryName(originalPath);
  156. string dataPath = parentFolder + "/" + AssetFolderName;
  157. if (!AssetDatabase.IsValidFolder(dataPath)) {
  158. AssetDatabase.CreateFolder(parentFolder, AssetFolderName);
  159. }
  160. string originalTextureName = System.IO.Path.GetFileNameWithoutExtension(originalPath);
  161. string texturePath = string.Format("{0}/{1}.png",
  162. dataPath, loader.GetPlaceholderTextureName(originalTextureName));
  163. Texture placeholderTexture = AssetDatabase.LoadAssetAtPath<Texture>(texturePath);
  164. if (placeholderTexture == null) {
  165. AssetDatabase.CopyAsset(originalPath, texturePath);
  166. const bool resizePhysically = true;
  167. TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(texturePath);
  168. const string defaultPlatform = "Default";
  169. TextureImporterPlatformSettings settings = importer.GetPlatformTextureSettings(defaultPlatform);
  170. settings.maxTextureSize = maxPlaceholderSize;
  171. importer.SetPlatformTextureSettings(settings);
  172. importer.maxTextureSize = maxPlaceholderSize;
  173. importer.isReadable = resizePhysically;
  174. importer.SaveAndReimport();
  175. if (resizePhysically) {
  176. bool hasOverrides = TextureImporterUtility.DisableOverrides(importer, out List<string> disabledPlatforms);
  177. Texture2D texture2D = AssetDatabase.LoadAssetAtPath<Texture2D>(texturePath);
  178. if (texture2D) {
  179. Color[] maxTextureSizePixels = texture2D.GetPixels();
  180. // SetPixels supports only uncompressed textures using certain formats.
  181. Texture2D uncompressedTexture =
  182. new Texture2D(texture2D.width, texture2D.height, TextureFormat.RGBA32, false);
  183. uncompressedTexture.SetPixels(maxTextureSizePixels);
  184. byte[] bytes = uncompressedTexture.EncodeToPNG();
  185. string targetPath = Application.dataPath + "/../" + texturePath;
  186. System.IO.File.WriteAllBytes(targetPath, bytes);
  187. importer.isReadable = false;
  188. importer.SaveAndReimport();
  189. EditorUtility.SetDirty(uncompressedTexture);
  190. AssetDatabase.SaveAssets();
  191. }
  192. if (hasOverrides)
  193. TextureImporterUtility.EnableOverrides(importer, disabledPlatforms);
  194. }
  195. placeholderTexture = AssetDatabase.LoadAssetAtPath<Texture>(texturePath);
  196. }
  197. UnityEngine.Object folderObject = AssetDatabase.LoadAssetAtPath(dataPath, typeof(UnityEngine.Object));
  198. if (folderObject != null) {
  199. EditorGUIUtility.PingObject(folderObject);
  200. }
  201. return placeholderTexture;
  202. }
  203. }
  204. public static StaticMethodImplementations staticMethods;
  205. void OnEnable () {
  206. atlasAsset = serializedObject.FindProperty("atlasAsset");
  207. maxPlaceholderSize = serializedObject.FindProperty("maxPlaceholderSize");
  208. placeholderMap = serializedObject.FindProperty("placeholderMap");
  209. unloadAfterSecondsUnused = serializedObject.FindProperty("unloadAfterSecondsUnused");
  210. loadedDataAtMaterial = serializedObject.FindProperty("loadedDataAtMaterial");
  211. placeholderTexturesLabel = new GUIContent("Placeholder Textures");
  212. loader = (GenericOnDemandTextureLoader<TargetReference, TextureRequest>)target;
  213. if (staticMethods == null)
  214. staticMethods = CreateStaticMethodImplementations();
  215. }
  216. #if NEWPLAYMODECALLBACKS
  217. static void OnPlaymodeChanged (PlayModeStateChange mode) {
  218. bool assignTargetTextures = mode == PlayModeStateChange.EnteredEditMode;
  219. #else
  220. static void OnPlaymodeChanged () {
  221. bool assignTargetTextures = !Application.isPlaying;
  222. #endif
  223. if (assignTargetTextures) {
  224. AssignTargetTexturesAtAllLoaders();
  225. }
  226. }
  227. public static void AssignTargetTexturesAtAllLoaders () {
  228. string[] loaderAssets = AssetDatabase.FindAssets("t:OnDemandTextureLoader");
  229. foreach (string loaderAsset in loaderAssets) {
  230. string assetPath = AssetDatabase.GUIDToAssetPath(loaderAsset);
  231. OnDemandTextureLoader loader = AssetDatabase.LoadAssetAtPath<OnDemandTextureLoader>(assetPath);
  232. AssignTargetTexturesAtLoader(loader);
  233. }
  234. }
  235. public static void AssignTargetTexturesAtLoader (OnDemandTextureLoader loader) {
  236. List<Material> placeholderMaterials;
  237. List<Material> nullTextureMaterials;
  238. bool anyPlaceholdersAssigned = loader.HasPlaceholderTexturesAssigned(out placeholderMaterials);
  239. bool anyMaterialNull = loader.HasNullMainTexturesAssigned(out nullTextureMaterials);
  240. if (anyPlaceholdersAssigned || anyMaterialNull) {
  241. Debug.Log("OnDemandTextureLoader detected placeholders assigned or null main textures at one or more materials. Resetting to target textures.", loader);
  242. AssetDatabase.StartAssetEditing();
  243. IEnumerable<Material> modifiedMaterials;
  244. loader.AssignTargetTextures(out modifiedMaterials);
  245. if (placeholderMaterials != null) {
  246. foreach (Material placeholderMaterial in placeholderMaterials) {
  247. EditorUtility.SetDirty(placeholderMaterial);
  248. }
  249. }
  250. if (nullTextureMaterials != null) {
  251. foreach (Material nullTextureMaterial in nullTextureMaterials) {
  252. EditorUtility.SetDirty(nullTextureMaterial);
  253. }
  254. }
  255. AssetDatabase.StopAssetEditing();
  256. AssetDatabase.SaveAssets();
  257. }
  258. }
  259. /// <summary>
  260. /// Override this method in your implementation subclass as follows.
  261. /// <code>
  262. /// protected override StaticMethodImplementations CreateStaticMethodImplementations () {
  263. /// return new YourStaticMethodImplementationsSubclass();
  264. /// }
  265. /// </code>
  266. /// </summary>
  267. protected abstract StaticMethodImplementations CreateStaticMethodImplementations ();
  268. /// <summary>Draws a single texture mapping entry in the Inspector.
  269. /// Can be overridden in subclasses where needed. Note that DrawSingleLineTargetTextureProperty
  270. /// can be overridden as well instead of overriding this method.
  271. /// Note that for the sake of space it should be drawn as a single line if possible.
  272. /// </summary>
  273. /// <param name="textureMapping">SerializedProperty pointing to a
  274. /// PlaceholderTextureMapping object of the placeholderMap array.</param>
  275. protected virtual void DrawPlaceholderMapping (SerializedProperty textureMapping) {
  276. EditorGUILayout.BeginHorizontal(GUILayout.Height(EditorGUIUtility.singleLineHeight + 5));
  277. var placeholderTextureProp = textureMapping.FindPropertyRelative("placeholderTexture");
  278. var targetTextureProp = textureMapping.FindPropertyRelative("targetTextureReference");
  279. GUILayout.Space(16f);
  280. EditorGUILayout.PropertyField(placeholderTextureProp, GUIContent.none);
  281. EditorGUIUtility.labelWidth = 1; // workaround since GUIContent.none below seems to be ignored
  282. DrawSingleLineTargetTextureProperty(targetTextureProp);
  283. EditorGUIUtility.labelWidth = 0; // change back to default
  284. EditorGUILayout.EndHorizontal();
  285. }
  286. /// <summary>Draws a single texture mapping TargetReference in the Inspector.
  287. /// Can be overridden in subclasses where needed. Note that this method is
  288. /// called inside a horizontal Inspector line of a BeginHorizontal() / EndHorizontal()
  289. /// pair, so it is limited to approximately half Inspector width.
  290. /// </summary>
  291. /// <param name="property">SerializedProperty pointing to a
  292. /// TargetReference object of the PlaceholderTextureMapping entry.</param>
  293. protected virtual void DrawSingleLineTargetTextureProperty (SerializedProperty property) {
  294. EditorGUILayout.PropertyField(property, GUIContent.none, true);
  295. }
  296. public override void OnInspectorGUI () {
  297. if (serializedObject.isEditingMultipleObjects) {
  298. DrawDefaultInspector();
  299. return;
  300. }
  301. serializedObject.Update();
  302. EditorGUILayout.PropertyField(atlasAsset);
  303. EditorGUILayout.PropertyField(maxPlaceholderSize);
  304. EditorGUILayout.PropertyField(unloadAfterSecondsUnused);
  305. placeholdersFoldout = EditorGUILayout.Foldout(placeholdersFoldout, placeholderTexturesLabel, true);
  306. if (placeholdersFoldout) {
  307. for (int m = 0, materialCount = placeholderMap.arraySize; m < materialCount; ++m) {
  308. // line below equals: PlaceholderTextureMapping[] materialTextures = placeholderMap[m].textures;
  309. SerializedProperty materialTextures = placeholderMap.GetArrayElementAtIndex(m).FindPropertyRelative("textures");
  310. for (int t = 0, textureCount = materialTextures.arraySize; t < textureCount; ++t) {
  311. // line below equals: PlaceholderTextureMapping textureMapping = materialTextures[t];
  312. SerializedProperty textureMapping = materialTextures.GetArrayElementAtIndex(t);
  313. DrawPlaceholderMapping(textureMapping);
  314. }
  315. }
  316. }
  317. if (GUILayout.Button(new GUIContent("Regenerate", "Re-initialize the placeholder texture maps."), EditorStyles.miniButton, GUILayout.Width(160f)))
  318. ReinitPlaceholderTextures(loader);
  319. GUILayout.Space(16f);
  320. EditorGUILayout.LabelField("Testing", EditorStyles.boldLabel);
  321. EditorGUILayout.BeginHorizontal(GUILayout.Height(EditorGUIUtility.singleLineHeight + 5));
  322. if (GUILayout.Button(new GUIContent("Assign Placeholders", "Assign placeholder textures (for testing)."), EditorStyles.miniButton, GUILayout.Width(160f)))
  323. AssignPlaceholderTextures(loader);
  324. if (GUILayout.Button(new GUIContent("Assign Normal Textures", "Re-assign target textures."), EditorStyles.miniButton, GUILayout.Width(160f)))
  325. AssignTargetTextures(loader);
  326. EditorGUILayout.EndHorizontal();
  327. if (!Application.isPlaying)
  328. serializedObject.ApplyModifiedProperties();
  329. }
  330. public void DeletePlaceholderTextures (GenericOnDemandTextureLoader<TargetReference, TextureRequest> loader) {
  331. foreach (var materialMap in loader.placeholderMap) {
  332. var textures = materialMap.textures;
  333. if (textures == null || textures.Length == 0)
  334. continue;
  335. Texture texture = textures[0].placeholderTexture;
  336. if (texture)
  337. AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(texture));
  338. }
  339. loader.Clear(clearAtlasAsset: false);
  340. AssetDatabase.SaveAssets();
  341. }
  342. public void ReinitPlaceholderTextures (GenericOnDemandTextureLoader<TargetReference, TextureRequest> loader) {
  343. AssignTargetTextures(loader);
  344. DeletePlaceholderTextures(loader);
  345. staticMethods.SetupForAtlasAsset(loader, loader.atlasAsset);
  346. EditorUtility.SetDirty(loader);
  347. AssetDatabase.SaveAssets();
  348. }
  349. public bool AssignPlaceholderTextures (GenericOnDemandTextureLoader<TargetReference, TextureRequest> loader) {
  350. // re-setup placeholders to ensure the mapping is up to date.
  351. staticMethods.SetupForAtlasAsset(loader, loader.atlasAsset);
  352. IEnumerable<Material> modifiedMaterials;
  353. return loader.AssignPlaceholderTextures(out modifiedMaterials);
  354. }
  355. public bool AssignTargetTextures (GenericOnDemandTextureLoader<TargetReference, TextureRequest> loader) {
  356. IEnumerable<Material> modifiedMaterials;
  357. return loader.AssignTargetTextures(out modifiedMaterials);
  358. }
  359. }
  360. }
  361. #endif