AnimationClipEditor.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2022 Kybernetik //
  2. #if UNITY_EDITOR
  3. using System;
  4. using System.Collections.Generic;
  5. using UnityEditor;
  6. using UnityEngine;
  7. using Object = UnityEngine.Object;
  8. namespace Animancer.Editor
  9. {
  10. /// <summary>[Editor-Only] [Pro-Only] A custom Inspector for <see cref="AnimationClip"/>s</summary>
  11. /// https://kybernetik.com.au/animancer/api/Animancer.Editor/AnimationClipEditor
  12. ///
  13. [CustomEditor(typeof(AnimationClip))]
  14. public class AnimationClipEditor : UnityEditor.Editor
  15. {
  16. /************************************************************************************************************************/
  17. private const string DefaultEditorTypeName = nameof(UnityEditor) + "." + nameof(AnimationClipEditor);
  18. private static readonly Type
  19. DefaultEditorType = typeof(UnityEditor.Editor).Assembly.GetType(DefaultEditorTypeName);
  20. /************************************************************************************************************************/
  21. private UnityEditor.Editor _DefaultEditor;
  22. private bool TryGetDefaultEditor(out UnityEditor.Editor editor)
  23. {
  24. if (_DefaultEditor == null)
  25. {
  26. if (DefaultEditorType == null || AnimancerEditorUtilities.IsChangingPlayMode)
  27. {
  28. editor = null;
  29. return false;
  30. }
  31. _DefaultEditor = CreateEditor(targets, DefaultEditorType);
  32. _DefaultEditor.hideFlags = HideFlags.DontSave;
  33. DestroyOnPlayModeStateChanged(_DefaultEditor);
  34. }
  35. editor = _DefaultEditor;
  36. return true;
  37. }
  38. /************************************************************************************************************************/
  39. protected virtual void OnDestroy()
  40. {
  41. _DestroyOnPlayModeStateChanged?.Remove(_DefaultEditor);
  42. DestroyImmediate(_DefaultEditor);
  43. }
  44. /************************************************************************************************************************/
  45. private static HashSet<Object> _DestroyOnPlayModeStateChanged;
  46. private static void DestroyOnPlayModeStateChanged(Object obj)
  47. {
  48. if (_DestroyOnPlayModeStateChanged == null)
  49. {
  50. _DestroyOnPlayModeStateChanged = new HashSet<Object>();
  51. EditorApplication.playModeStateChanged += (change) =>
  52. {
  53. foreach (var destroy in _DestroyOnPlayModeStateChanged)
  54. DestroyImmediate(destroy);
  55. _DestroyOnPlayModeStateChanged.Clear();
  56. };
  57. }
  58. _DestroyOnPlayModeStateChanged.Add(obj);
  59. }
  60. /************************************************************************************************************************/
  61. /// <summary>Draws the regular Inspector then adds a better preview for <see cref="Sprite"/> animations.</summary>
  62. /// <remarks>Called by the Unity editor to draw the custom Inspector GUI elements.</remarks>
  63. public override void OnInspectorGUI()
  64. {
  65. if (DefaultEditorType == null)
  66. {
  67. EditorGUILayout.HelpBox(
  68. $"Unable to find type '{DefaultEditorTypeName}' in '{typeof(UnityEditor.Editor).Assembly}'." +
  69. $" The {nameof(AnimationClipEditor)} script will need to be fixed" +
  70. $" or you can simply delete it to use Unity's regular {nameof(AnimationClip)} Inspector.", MessageType.Error);
  71. const string Label = "Delete " + nameof(AnimationClipEditor) + " Script";
  72. if (GUILayout.Button(Label))
  73. {
  74. if (EditorUtility.DisplayDialog(Label,
  75. $"Are you sure you want to delete the {nameof(AnimationClipEditor)} script?" +
  76. $" This operation cannot be undone.",
  77. "Delete", "Cancel"))
  78. {
  79. var script = MonoScript.FromScriptableObject(this);
  80. var path = AssetDatabase.GetAssetPath(script);
  81. AssetDatabase.DeleteAsset(path);
  82. }
  83. }
  84. return;
  85. }
  86. if (TryGetDefaultEditor(out var editor))
  87. editor.OnInspectorGUI();
  88. if (GUILayout.Button("Open Animation Window"))
  89. EditorApplication.ExecuteMenuItem("Window/Animation/Animation");
  90. if (GUILayout.Button("Open Animancer Tools"))
  91. Tools.AnimancerToolsWindow.Open();
  92. var targets = this.targets;
  93. if (targets.Length == 1)
  94. {
  95. var clip = GetTargetClip(out var type);
  96. DrawEvents(clip);
  97. if (type == AnimationType.Sprite)
  98. {
  99. InitializeSpritePreview(editor, clip);
  100. DrawSpriteFrames(clip);
  101. }
  102. }
  103. }
  104. /************************************************************************************************************************/
  105. private AnimationClip GetTargetClip(out AnimationType type)
  106. {
  107. var clip = (AnimationClip)target;
  108. type = AnimationBindings.GetAnimationType(clip);
  109. return clip;
  110. }
  111. /************************************************************************************************************************/
  112. [SerializeField]
  113. private bool _ShowEvents = true;
  114. private void DrawEvents(AnimationClip clip)
  115. {
  116. var events = clip.events;
  117. if (events == null ||
  118. events.Length == 0)
  119. return;
  120. _ShowEvents = EditorGUILayout.Foldout(_ShowEvents, "Events", true);
  121. if (!_ShowEvents)
  122. return;
  123. using (new EditorGUI.DisabledScope(true))
  124. {
  125. EditorGUI.indentLevel++;
  126. for (int i = 0; i < events.Length; i++)
  127. {
  128. var animationEvent = events[i];
  129. EditorGUILayout.FloatField(animationEvent.functionName, animationEvent.time);
  130. EditorGUI.indentLevel++;
  131. EditorGUILayout.IntField("Int", animationEvent.intParameter);
  132. EditorGUILayout.FloatField("Float", animationEvent.floatParameter);
  133. EditorGUILayout.TextField("String", animationEvent.stringParameter);
  134. EditorGUILayout.ObjectField("Object", animationEvent.objectReferenceParameter, typeof(Object), false);
  135. EditorGUI.indentLevel--;
  136. }
  137. EditorGUI.indentLevel--;
  138. }
  139. }
  140. /************************************************************************************************************************/
  141. [NonSerialized]
  142. private bool _HasInitializedSpritePreview;
  143. private void InitializeSpritePreview(UnityEditor.Editor editor, AnimationClip clip)
  144. {
  145. if (_HasInitializedSpritePreview)
  146. return;
  147. _HasInitializedSpritePreview = true;
  148. // Get the avatar preview.
  149. var field = editor.GetType().GetField("m_AvatarPreview", AnimancerEditorUtilities.InstanceBindings);
  150. if (field == null)
  151. return;
  152. var preview = field.GetValue(editor);
  153. if (preview == null)
  154. return;
  155. var previewType = preview.GetType();
  156. // Make sure a proper preview object isn't already assigned.
  157. var previewObject = previewType.GetProperty("PreviewObject", AnimancerEditorUtilities.InstanceBindings);
  158. if (previewObject == null)
  159. return;
  160. var previewGameObject = previewObject.GetValue(preview) as GameObject;
  161. if (previewGameObject != null &&
  162. previewGameObject.GetComponentInChildren<Renderer>() != null)
  163. return;
  164. // Get the SetPreview method.
  165. var method = previewType.GetMethod("SetPreview",
  166. AnimancerEditorUtilities.InstanceBindings, null,
  167. new Type[] { typeof(GameObject) }, null);
  168. if (method == null)
  169. return;
  170. // Get the Sprite from the target animation's first keyframe.
  171. var keyframes = GetSpriteReferences(clip);
  172. if (keyframes == null ||
  173. keyframes.Length == 0)
  174. return;
  175. var sprite = keyframes[0].value as Sprite;
  176. if (sprite == null)
  177. return;
  178. // Create an object with an Animator and SpriteRenderer.
  179. // The Sprite must be assigned for it to be accepted as the preview object.
  180. var gameObject = EditorUtility.CreateGameObjectWithHideFlags("SpritePreview",
  181. HideFlags.HideInHierarchy | HideFlags.DontSave);
  182. gameObject.AddComponent<Animator>();
  183. gameObject.AddComponent<SpriteRenderer>().sprite = sprite;
  184. // Set it as the preview object (which creates a copy of it) and destroy it.
  185. method.Invoke(preview, new object[] { gameObject });
  186. DestroyImmediate(gameObject);
  187. }
  188. /************************************************************************************************************************/
  189. private static ConversionCache<int, string> _FrameCache;
  190. private static ConversionCache<float, string> _TimeCache;
  191. private static void DrawSpriteFrames(AnimationClip clip)
  192. {
  193. var keyframes = GetSpriteReferences(clip);
  194. if (keyframes == null)
  195. return;
  196. for (int i = 0; i < keyframes.Length; i++)
  197. {
  198. var keyframe = keyframes[i];
  199. var sprite = keyframe.value as Sprite;
  200. if (sprite != null)
  201. {
  202. if (_FrameCache == null)
  203. {
  204. _FrameCache = new ConversionCache<int, string>(
  205. (value) => $"Frame: {value}");
  206. _TimeCache = new ConversionCache<float, string>(
  207. (value) => $"Time: {value}s");
  208. }
  209. var texture = sprite.texture;
  210. var area = GUILayoutUtility.GetRect(0, AnimancerGUI.LineHeight * 4);
  211. var width = area.width;
  212. var rect = sprite.rect;
  213. area.width = area.height * rect.width / rect.height;
  214. rect.x /= texture.width;
  215. rect.y /= texture.height;
  216. rect.width /= texture.width;
  217. rect.height /= texture.height;
  218. GUI.DrawTextureWithTexCoords(area, texture, rect);
  219. var offset = area.width + AnimancerGUI.StandardSpacing;
  220. area.x += offset;
  221. area.width = width - offset;
  222. area.height = AnimancerGUI.LineHeight;
  223. area.y += Mathf.Round(area.height * 0.5f);
  224. GUI.Label(area, _FrameCache.Convert(i));
  225. AnimancerGUI.NextVerticalArea(ref area);
  226. GUI.Label(area, _TimeCache.Convert(keyframe.time));
  227. AnimancerGUI.NextVerticalArea(ref area);
  228. GUI.Label(area, sprite.name);
  229. }
  230. }
  231. }
  232. /************************************************************************************************************************/
  233. private static ObjectReferenceKeyframe[] GetSpriteReferences(AnimationClip clip)
  234. {
  235. var bindings = AnimationBindings.GetBindings(clip);
  236. for (int i = 0; i < bindings.Length; i++)
  237. {
  238. var binding = bindings[i];
  239. if (binding.path == "" &&
  240. binding.type == typeof(SpriteRenderer) &&
  241. binding.propertyName == "m_Sprite")
  242. return AnimationUtility.GetObjectReferenceCurve(clip, binding);
  243. }
  244. return null;
  245. }
  246. /************************************************************************************************************************/
  247. #region Redirects
  248. /************************************************************************************************************************/
  249. /// <inheritdoc/>
  250. public override void DrawPreview(Rect previewArea)
  251. {
  252. if (TryGetDefaultEditor(out var editor))
  253. editor.DrawPreview(previewArea);
  254. else
  255. base.DrawPreview(previewArea);
  256. }
  257. /************************************************************************************************************************/
  258. /// <inheritdoc/>
  259. public override string GetInfoString()
  260. {
  261. if (TryGetDefaultEditor(out var editor))
  262. return editor.GetInfoString();
  263. else
  264. return base.GetInfoString();
  265. }
  266. /************************************************************************************************************************/
  267. /// <inheritdoc/>
  268. public override GUIContent GetPreviewTitle()
  269. {
  270. if (TryGetDefaultEditor(out var editor))
  271. return editor.GetPreviewTitle();
  272. else
  273. return base.GetPreviewTitle();
  274. }
  275. /************************************************************************************************************************/
  276. /// <inheritdoc/>
  277. public override bool HasPreviewGUI()
  278. {
  279. if (TryGetDefaultEditor(out var editor))
  280. return editor.HasPreviewGUI();
  281. else
  282. return base.HasPreviewGUI();
  283. }
  284. /************************************************************************************************************************/
  285. /// <inheritdoc/>
  286. public override void OnInteractivePreviewGUI(Rect area, GUIStyle background)
  287. {
  288. if (TryGetDefaultEditor(out var editor))
  289. editor.OnInteractivePreviewGUI(area, background);
  290. else
  291. base.OnInteractivePreviewGUI(area, background);
  292. }
  293. /************************************************************************************************************************/
  294. /// <inheritdoc/>
  295. public override void OnPreviewGUI(Rect area, GUIStyle background)
  296. {
  297. if (TryGetDefaultEditor(out var editor))
  298. editor.OnPreviewGUI(area, background);
  299. else
  300. base.OnPreviewGUI(area, background);
  301. }
  302. /************************************************************************************************************************/
  303. /// <inheritdoc/>
  304. public override void OnPreviewSettings()
  305. {
  306. if (TryGetDefaultEditor(out var editor))
  307. editor.OnPreviewSettings();
  308. else
  309. base.OnPreviewSettings();
  310. }
  311. /************************************************************************************************************************/
  312. /// <inheritdoc/>
  313. public override void ReloadPreviewInstances()
  314. {
  315. if (TryGetDefaultEditor(out var editor))
  316. editor.ReloadPreviewInstances();
  317. else
  318. base.ReloadPreviewInstances();
  319. }
  320. /************************************************************************************************************************/
  321. /// <inheritdoc/>
  322. public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height)
  323. {
  324. if (TryGetDefaultEditor(out var editor))
  325. return editor.RenderStaticPreview(assetPath, subAssets, width, height);
  326. else
  327. return base.RenderStaticPreview(assetPath, subAssets, width, height);
  328. }
  329. /************************************************************************************************************************/
  330. /// <inheritdoc/>
  331. public override bool RequiresConstantRepaint()
  332. {
  333. if (TryGetDefaultEditor(out var editor))
  334. return editor.RequiresConstantRepaint();
  335. else
  336. return base.RequiresConstantRepaint();
  337. }
  338. /************************************************************************************************************************/
  339. /// <inheritdoc/>
  340. public override bool UseDefaultMargins()
  341. {
  342. if (TryGetDefaultEditor(out var editor))
  343. return editor.UseDefaultMargins();
  344. else
  345. return base.UseDefaultMargins();
  346. }
  347. /************************************************************************************************************************/
  348. #endregion
  349. /************************************************************************************************************************/
  350. }
  351. }
  352. #endif