AnimationWindow.cs 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using BansheeEngine;
  7. namespace BansheeEditor
  8. {
  9. /** @addtogroup Windows
  10. * @{
  11. */
  12. /// <summary>
  13. /// Displays animation curve editor window.
  14. /// </summary>
  15. [DefaultSize(900, 500)]
  16. internal class AnimationWindow : EditorWindow
  17. {
  18. private const int FIELD_DISPLAY_WIDTH = 300;
  19. private const int DRAG_START_DISTANCE = 3;
  20. private const float DRAG_SCALE = 1.0f;
  21. private const float ZOOM_SCALE = 0.1f/120.0f; // One scroll step is usually 120 units, we want 1/10 of that
  22. private SceneObject selectedSO;
  23. /// <summary>
  24. /// Scene object for which are we currently changing the animation for.
  25. /// </summary>
  26. internal SceneObject SelectedSO
  27. {
  28. get { return selectedSO; }
  29. }
  30. #region Overrides
  31. /// <summary>
  32. /// Opens the animation window.
  33. /// </summary>
  34. [MenuItem("Windows/Animation", ButtonModifier.CtrlAlt, ButtonCode.A, 6000)]
  35. private static void OpenGameWindow()
  36. {
  37. OpenWindow<AnimationWindow>();
  38. }
  39. /// <inheritdoc/>
  40. protected override LocString GetDisplayName()
  41. {
  42. return new LocEdString("Animation");
  43. }
  44. private void OnInitialize()
  45. {
  46. Selection.OnSelectionChanged += OnSelectionChanged;
  47. UpdateSelectedSO(true);
  48. }
  49. private void OnEditorUpdate()
  50. {
  51. if (selectedSO == null)
  52. return;
  53. HandleDragAndZoomInput();
  54. }
  55. private void OnDestroy()
  56. {
  57. Selection.OnSelectionChanged -= OnSelectionChanged;
  58. if (selectedSO != null)
  59. {
  60. EditorInput.OnPointerPressed -= OnPointerPressed;
  61. EditorInput.OnPointerMoved -= OnPointerMoved;
  62. EditorInput.OnPointerReleased -= OnPointerReleased;
  63. EditorInput.OnButtonUp -= OnButtonUp;
  64. }
  65. }
  66. protected override void WindowResized(int width, int height)
  67. {
  68. if (selectedSO == null)
  69. return;
  70. ResizeGUI(width, height);
  71. }
  72. #endregion
  73. #region GUI
  74. private GUIButton playButton;
  75. private GUIButton recordButton;
  76. private GUIButton prevFrameButton;
  77. private GUIIntField frameInputField;
  78. private GUIButton nextFrameButton;
  79. private GUIButton addKeyframeButton;
  80. private GUIButton addEventButton;
  81. private GUIButton optionsButton;
  82. private GUIButton addPropertyBtn;
  83. private GUIButton delPropertyBtn;
  84. private GUILayout buttonLayout;
  85. private int buttonLayoutHeight;
  86. private int scrollBarWidth;
  87. private int scrollBarHeight;
  88. private GUIResizeableScrollBarH horzScrollBar;
  89. private GUIResizeableScrollBarV vertScrollBar;
  90. private GUIPanel editorPanel;
  91. private GUIAnimFieldDisplay guiFieldDisplay;
  92. private GUICurveEditor guiCurveEditor;
  93. private void RebuildGUI()
  94. {
  95. GUI.Clear();
  96. if (selectedSO == null)
  97. {
  98. GUILabel warningLbl = new GUILabel(new LocEdString("Select an object to animate in the Hierarchy or Scene windows."));
  99. GUILayoutY vertLayout = GUI.AddLayoutY();
  100. vertLayout.AddFlexibleSpace();
  101. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  102. vertLayout.AddFlexibleSpace();
  103. horzLayout.AddFlexibleSpace();
  104. horzLayout.AddElement(warningLbl);
  105. horzLayout.AddFlexibleSpace();
  106. return;
  107. }
  108. // Top button row
  109. GUIContent playIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Play),
  110. new LocEdString("Play"));
  111. GUIContent recordIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Record),
  112. new LocEdString("Record"));
  113. GUIContent prevFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameBack),
  114. new LocEdString("Previous frame"));
  115. GUIContent nextFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameForward),
  116. new LocEdString("Next frame"));
  117. GUIContent addKeyframeIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddKeyframe),
  118. new LocEdString("Add keyframe"));
  119. GUIContent addEventIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddEvent),
  120. new LocEdString("Add event"));
  121. GUIContent optionsIcon = new GUIContent(EditorBuiltin.GetLibraryWindowIcon(LibraryWindowIcon.Options),
  122. new LocEdString("Options"));
  123. playButton = new GUIButton(playIcon);
  124. recordButton = new GUIButton(recordIcon);
  125. prevFrameButton = new GUIButton(prevFrameIcon);
  126. frameInputField = new GUIIntField();
  127. nextFrameButton = new GUIButton(nextFrameIcon);
  128. addKeyframeButton = new GUIButton(addKeyframeIcon);
  129. addEventButton = new GUIButton(addEventIcon);
  130. optionsButton = new GUIButton(optionsIcon);
  131. playButton.OnClick += () =>
  132. {
  133. // TODO
  134. // - Record current state of the scene object hierarchy
  135. // - Evaluate all curves manually and update them
  136. // - On end, restore original values of the scene object hierarchy
  137. };
  138. recordButton.OnClick += () =>
  139. {
  140. // TODO
  141. // - Every frame read back current values of all the current curve's properties and assign it to the current frame
  142. };
  143. prevFrameButton.OnClick += () =>
  144. {
  145. SetCurrentFrame(currentFrameIdx - 1);
  146. };
  147. frameInputField.OnChanged += SetCurrentFrame;
  148. nextFrameButton.OnClick += () =>
  149. {
  150. SetCurrentFrame(currentFrameIdx + 1);
  151. };
  152. addKeyframeButton.OnClick += () =>
  153. {
  154. guiCurveEditor.AddKeyFrameAtMarker();
  155. };
  156. addEventButton.OnClick += () =>
  157. {
  158. guiCurveEditor.AddEventAtMarker();
  159. };
  160. optionsButton.OnClick += () =>
  161. {
  162. Vector2I openPosition = ScreenToWindowPos(Input.PointerPosition);
  163. AnimationOptions dropDown = DropDownWindow.Open<AnimationOptions>(this, openPosition);
  164. dropDown.Initialize(this);
  165. };
  166. // Property buttons
  167. addPropertyBtn = new GUIButton(new LocEdString("Add property"));
  168. delPropertyBtn = new GUIButton(new LocEdString("Delete selected"));
  169. addPropertyBtn.OnClick += () =>
  170. {
  171. Action openPropertyWindow = () =>
  172. {
  173. Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
  174. FieldSelectionWindow fieldSelection = DropDownWindow.Open<FieldSelectionWindow>(this, windowPos);
  175. fieldSelection.OnFieldSelected += OnFieldAdded;
  176. };
  177. if (clipInfo.clip == null)
  178. {
  179. LocEdString title = new LocEdString("Warning");
  180. LocEdString message =
  181. new LocEdString("Selected object doesn't have an animation clip assigned. Would you like to create" +
  182. " a new animation clip?");
  183. DialogBox.Open(title, message, DialogBox.Type.YesNoCancel, type =>
  184. {
  185. if (type == DialogBox.ResultType.Yes)
  186. {
  187. string[] clipSavePaths;
  188. if (BrowseDialog.OpenFile(ProjectLibrary.ResourceFolder, "", false, out clipSavePaths))
  189. {
  190. if (clipSavePaths.Length > 0)
  191. {
  192. AnimationClip newClip = new AnimationClip();
  193. ProjectLibrary.Create(newClip, clipSavePaths[0]);
  194. LoadAnimClip(newClip);
  195. Animation animation = selectedSO.GetComponent<Animation>();
  196. if (animation == null)
  197. animation = selectedSO.AddComponent<Animation>();
  198. animation.DefaultClip = newClip;
  199. EditorApplication.SetSceneDirty();
  200. openPropertyWindow();
  201. }
  202. }
  203. }
  204. });
  205. }
  206. else
  207. {
  208. if (clipInfo.isImported)
  209. {
  210. LocEdString title = new LocEdString("Warning");
  211. LocEdString message =
  212. new LocEdString("You cannot add/edit/remove curves from animation clips that" +
  213. " are imported from an external file.");
  214. DialogBox.Open(title, message, DialogBox.Type.OK);
  215. }
  216. else
  217. openPropertyWindow();
  218. }
  219. };
  220. delPropertyBtn.OnClick += () =>
  221. {
  222. if (clipInfo.clip == null)
  223. return;
  224. if (clipInfo.isImported)
  225. {
  226. LocEdString title = new LocEdString("Warning");
  227. LocEdString message =
  228. new LocEdString("You cannot add/edit/remove curves from animation clips that" +
  229. " are imported from an external file.");
  230. DialogBox.Open(title, message, DialogBox.Type.OK);
  231. }
  232. else
  233. {
  234. LocEdString title = new LocEdString("Warning");
  235. LocEdString message = new LocEdString("Are you sure you want to remove all selected fields?");
  236. DialogBox.Open(title, message, DialogBox.Type.YesNo, x =>
  237. {
  238. if (x == DialogBox.ResultType.Yes)
  239. {
  240. RemoveSelectedFields();
  241. }
  242. });
  243. }
  244. };
  245. GUILayout mainLayout = GUI.AddLayoutY();
  246. buttonLayout = mainLayout.AddLayoutX();
  247. buttonLayout.AddSpace(5);
  248. buttonLayout.AddElement(playButton);
  249. buttonLayout.AddElement(recordButton);
  250. buttonLayout.AddSpace(5);
  251. buttonLayout.AddElement(prevFrameButton);
  252. buttonLayout.AddElement(frameInputField);
  253. buttonLayout.AddElement(nextFrameButton);
  254. buttonLayout.AddSpace(5);
  255. buttonLayout.AddElement(addKeyframeButton);
  256. buttonLayout.AddElement(addEventButton);
  257. buttonLayout.AddSpace(5);
  258. buttonLayout.AddElement(optionsButton);
  259. buttonLayout.AddFlexibleSpace();
  260. buttonLayoutHeight = playButton.Bounds.height;
  261. GUILayout contentLayout = mainLayout.AddLayoutX();
  262. GUILayout fieldDisplayLayout = contentLayout.AddLayoutY(GUIOption.FixedWidth(FIELD_DISPLAY_WIDTH));
  263. guiFieldDisplay = new GUIAnimFieldDisplay(fieldDisplayLayout, FIELD_DISPLAY_WIDTH,
  264. Height - buttonLayoutHeight * 2, selectedSO);
  265. guiFieldDisplay.OnEntrySelected += OnFieldSelected;
  266. GUILayout bottomButtonLayout = fieldDisplayLayout.AddLayoutX();
  267. bottomButtonLayout.AddElement(addPropertyBtn);
  268. bottomButtonLayout.AddElement(delPropertyBtn);
  269. horzScrollBar = new GUIResizeableScrollBarH();
  270. horzScrollBar.OnScrollOrResize += OnHorzScrollOrResize;
  271. vertScrollBar = new GUIResizeableScrollBarV();
  272. vertScrollBar.OnScrollOrResize += OnVertScrollOrResize;
  273. GUILayout curveLayout = contentLayout.AddLayoutY();
  274. GUILayout curveLayoutHorz = curveLayout.AddLayoutX();
  275. GUILayout horzScrollBarLayout = curveLayout.AddLayoutX();
  276. horzScrollBarLayout.AddElement(horzScrollBar);
  277. horzScrollBarLayout.AddFlexibleSpace();
  278. editorPanel = curveLayoutHorz.AddPanel();
  279. curveLayoutHorz.AddElement(vertScrollBar);
  280. curveLayoutHorz.AddFlexibleSpace();
  281. scrollBarHeight = horzScrollBar.Bounds.height;
  282. scrollBarWidth = vertScrollBar.Bounds.width;
  283. Vector2I curveEditorSize = GetCurveEditorSize();
  284. guiCurveEditor = new GUICurveEditor(this, editorPanel, curveEditorSize.x, curveEditorSize.y);
  285. guiCurveEditor.OnFrameSelected += OnFrameSelected;
  286. guiCurveEditor.OnEventAdded += OnEventsChanged;
  287. guiCurveEditor.OnEventModified += EditorApplication.SetProjectDirty;
  288. guiCurveEditor.OnEventDeleted += OnEventsChanged;
  289. guiCurveEditor.OnCurveModified += EditorApplication.SetProjectDirty;
  290. guiCurveEditor.Redraw();
  291. horzScrollBar.SetWidth(curveEditorSize.x);
  292. vertScrollBar.SetHeight(curveEditorSize.y);
  293. UpdateScrollBarSize();
  294. }
  295. private void ResizeGUI(int width, int height)
  296. {
  297. guiFieldDisplay.SetSize(FIELD_DISPLAY_WIDTH, height - buttonLayoutHeight * 2);
  298. Vector2I curveEditorSize = GetCurveEditorSize();
  299. guiCurveEditor.SetSize(curveEditorSize.x, curveEditorSize.y);
  300. guiCurveEditor.Redraw();
  301. horzScrollBar.SetWidth(curveEditorSize.x);
  302. vertScrollBar.SetHeight(curveEditorSize.y);
  303. UpdateScrollBarSize();
  304. UpdateScrollBarPosition();
  305. }
  306. #endregion
  307. #region Scroll, drag, zoom
  308. private Vector2I dragStartPos;
  309. private bool isButtonHeld;
  310. private bool isDragInProgress;
  311. private float zoomAmount;
  312. private void HandleDragAndZoomInput()
  313. {
  314. // Handle middle mouse dragging
  315. if (isDragInProgress)
  316. {
  317. float dragX = Input.GetAxisValue(InputAxis.MouseX) * DRAG_SCALE;
  318. float dragY = Input.GetAxisValue(InputAxis.MouseY) * DRAG_SCALE;
  319. Vector2 offset = guiCurveEditor.Offset;
  320. offset.x = Math.Max(0.0f, offset.x + dragX);
  321. offset.y -= dragY;
  322. guiCurveEditor.Offset = offset;
  323. UpdateScrollBarSize();
  324. UpdateScrollBarPosition();
  325. }
  326. // Handle zoom in/out
  327. float scroll = Input.GetAxisValue(InputAxis.MouseZ);
  328. if (scroll != 0.0f)
  329. {
  330. Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
  331. Vector2 curvePos;
  332. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  333. {
  334. float zoom = scroll * ZOOM_SCALE;
  335. Zoom(curvePos, zoom);
  336. }
  337. }
  338. }
  339. private void SetVertScrollbarProperties(float position, float size)
  340. {
  341. Vector2 visibleRange = guiCurveEditor.Range;
  342. Vector2 totalRange = GetTotalRange();
  343. visibleRange.y = totalRange.y*size;
  344. guiCurveEditor.Range = visibleRange;
  345. float scrollableRange = totalRange.y - visibleRange.y;
  346. Vector2 offset = guiCurveEditor.Offset;
  347. offset.y = -scrollableRange * (position * 2.0f - 1.0f);
  348. guiCurveEditor.Offset = offset;
  349. }
  350. private void SetHorzScrollbarProperties(float position, float size)
  351. {
  352. Vector2 visibleRange = guiCurveEditor.Range;
  353. Vector2 totalRange = GetTotalRange();
  354. visibleRange.x = totalRange.x * size;
  355. guiCurveEditor.Range = visibleRange;
  356. float scrollableRange = totalRange.x - visibleRange.x;
  357. Vector2 offset = guiCurveEditor.Offset;
  358. offset.x = scrollableRange * position;
  359. guiCurveEditor.Offset = offset;
  360. }
  361. private void UpdateScrollBarSize()
  362. {
  363. Vector2 visibleRange = guiCurveEditor.Range;
  364. Vector2 totalRange = GetTotalRange();
  365. horzScrollBar.HandleSize = visibleRange.x / totalRange.x;
  366. vertScrollBar.HandleSize = visibleRange.y / totalRange.y;
  367. }
  368. private void UpdateScrollBarPosition()
  369. {
  370. Vector2 visibleRange = guiCurveEditor.Range;
  371. Vector2 totalRange = GetTotalRange();
  372. Vector2 scrollableRange = totalRange - visibleRange;
  373. Vector2 offset = guiCurveEditor.Offset;
  374. if (scrollableRange.x > 0.0f)
  375. horzScrollBar.Position = offset.x / scrollableRange.x;
  376. else
  377. horzScrollBar.Position = 0.0f;
  378. if (scrollableRange.y > 0.0f)
  379. {
  380. float pos = offset.y/scrollableRange.y;
  381. float sign = MathEx.Sign(pos);
  382. pos = sign*MathEx.Clamp01(MathEx.Abs(pos));
  383. pos = (1.0f - pos) /2.0f;
  384. vertScrollBar.Position = pos;
  385. }
  386. else
  387. vertScrollBar.Position = 0.0f;
  388. }
  389. private Vector2 GetZoomedRange()
  390. {
  391. float zoomLevel = MathEx.Pow(2, zoomAmount);
  392. Vector2 optimalRange = GetOptimalRange();
  393. return optimalRange / zoomLevel;
  394. }
  395. private Vector2 GetTotalRange()
  396. {
  397. // Return optimal range (that covers the visible curve)
  398. Vector2 optimalRange = GetOptimalRange();
  399. // Increase range in case user zoomed out
  400. Vector2 zoomedRange = GetZoomedRange();
  401. return Vector2.Max(optimalRange, zoomedRange);
  402. }
  403. private void Zoom(Vector2 curvePos, float amount)
  404. {
  405. // Increase or decrease the visible range depending on zoom level
  406. Vector2 oldZoomedRange = GetZoomedRange();
  407. zoomAmount = MathEx.Clamp(zoomAmount + amount, -10.0f, 10.0f);
  408. Vector2 zoomedRange = GetZoomedRange();
  409. Vector2 zoomedDiff = zoomedRange - oldZoomedRange;
  410. Vector2 currentRange = guiCurveEditor.Range;
  411. Vector2 newRange = currentRange + zoomedDiff;
  412. guiCurveEditor.Range = newRange;
  413. // When zooming, make sure to focus on the point provided, so adjust the offset
  414. Vector2 rangeScale = newRange;
  415. rangeScale.x /= currentRange.x;
  416. rangeScale.y /= currentRange.y;
  417. Vector2 relativeCurvePos = curvePos - guiCurveEditor.Offset;
  418. Vector2 newCurvePos = relativeCurvePos * rangeScale;
  419. Vector2 diff = newCurvePos - relativeCurvePos;
  420. guiCurveEditor.Offset -= diff;
  421. UpdateScrollBarSize();
  422. UpdateScrollBarPosition();
  423. }
  424. #endregion
  425. #region Curve save/load
  426. private EditorAnimClipInfo clipInfo;
  427. private void LoadAnimClip(AnimationClip clip)
  428. {
  429. EditorPersistentData persistentData = EditorApplication.PersistentData;
  430. if (persistentData.dirtyAnimClips.TryGetValue(clip.UUID, out clipInfo))
  431. {
  432. // If an animation clip is imported, we don't care about it's cached curve values as they could have changed
  433. // since last modification, so we re-load the clip. But we persist the events as those can only be set
  434. // within the editor.
  435. if (clipInfo.isImported)
  436. {
  437. EditorAnimClipInfo newClipInfo = EditorAnimClipInfo.Create(clip);
  438. newClipInfo.events = clipInfo.events;
  439. }
  440. }
  441. else
  442. clipInfo = EditorAnimClipInfo.Create(clip);
  443. persistentData.dirtyAnimClips[clip.UUID] = clipInfo;
  444. foreach (var curve in clipInfo.curves)
  445. guiFieldDisplay.AddField(new AnimFieldInfo(curve.Key, curve.Value.type, !clipInfo.isImported));
  446. guiCurveEditor.Events = clipInfo.events;
  447. guiCurveEditor.DisableCurveEdit = clipInfo.isImported;
  448. SetCurrentFrame(0);
  449. }
  450. private void UpdateSelectedSO(bool force)
  451. {
  452. SceneObject so = Selection.SceneObject;
  453. if (selectedSO != so || force)
  454. {
  455. if (selectedSO != null && so == null)
  456. {
  457. EditorInput.OnPointerPressed -= OnPointerPressed;
  458. EditorInput.OnPointerMoved -= OnPointerMoved;
  459. EditorInput.OnPointerReleased -= OnPointerReleased;
  460. EditorInput.OnButtonUp -= OnButtonUp;
  461. }
  462. else if (selectedSO == null && so != null)
  463. {
  464. EditorInput.OnPointerPressed += OnPointerPressed;
  465. EditorInput.OnPointerMoved += OnPointerMoved;
  466. EditorInput.OnPointerReleased += OnPointerReleased;
  467. EditorInput.OnButtonUp += OnButtonUp;
  468. }
  469. zoomAmount = 0.0f;
  470. selectedSO = so;
  471. selectedFields.Clear();
  472. clipInfo = null;
  473. RebuildGUI();
  474. // Load existing clip if one exists
  475. if (selectedSO != null)
  476. {
  477. Animation animation = selectedSO.GetComponent<Animation>();
  478. if (animation != null)
  479. {
  480. AnimationClip clip = animation.DefaultClip;
  481. if (clip != null)
  482. LoadAnimClip(clip);
  483. }
  484. }
  485. if(clipInfo == null)
  486. clipInfo = new EditorAnimClipInfo();
  487. UpdateDisplayedCurves(true);
  488. }
  489. }
  490. #endregion
  491. #region Curve display
  492. private int currentFrameIdx;
  493. private int fps = 1;
  494. internal int FPS
  495. {
  496. get { return fps; }
  497. set { guiCurveEditor.SetFPS(value); fps = MathEx.Max(value, 1); }
  498. }
  499. private void SetCurrentFrame(int frameIdx)
  500. {
  501. currentFrameIdx = Math.Max(0, frameIdx);
  502. frameInputField.Value = currentFrameIdx;
  503. guiCurveEditor.SetMarkedFrame(currentFrameIdx);
  504. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  505. List<GUIAnimFieldPathValue> values = new List<GUIAnimFieldPathValue>();
  506. foreach (var kvp in clipInfo.curves)
  507. {
  508. string suffix;
  509. SerializableProperty property = Animation.FindProperty(selectedSO, kvp.Key, out suffix);
  510. if (property != null)
  511. {
  512. GUIAnimFieldPathValue fieldValue = new GUIAnimFieldPathValue();
  513. fieldValue.path = kvp.Key;
  514. switch (kvp.Value.type)
  515. {
  516. case SerializableProperty.FieldType.Vector2:
  517. {
  518. Vector2 value = new Vector2();
  519. for (int i = 0; i < 2; i++)
  520. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  521. fieldValue.value = value;
  522. }
  523. break;
  524. case SerializableProperty.FieldType.Vector3:
  525. {
  526. Vector3 value = new Vector3();
  527. for (int i = 0; i < 3; i++)
  528. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  529. fieldValue.value = value;
  530. }
  531. break;
  532. case SerializableProperty.FieldType.Vector4:
  533. {
  534. Vector4 value = new Vector4();
  535. for (int i = 0; i < 4; i++)
  536. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  537. fieldValue.value = value;
  538. }
  539. break;
  540. case SerializableProperty.FieldType.Color:
  541. {
  542. Color value = new Color();
  543. for (int i = 0; i < 4; i++)
  544. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  545. fieldValue.value = value;
  546. }
  547. break;
  548. case SerializableProperty.FieldType.Bool:
  549. case SerializableProperty.FieldType.Int:
  550. case SerializableProperty.FieldType.Float:
  551. fieldValue.value = kvp.Value.curves[0].Evaluate(time, false); ;
  552. break;
  553. }
  554. values.Add(fieldValue);
  555. }
  556. }
  557. guiFieldDisplay.SetDisplayValues(values.ToArray());
  558. }
  559. private EdAnimationCurve[] GetDisplayedCurves()
  560. {
  561. List<EdAnimationCurve> curvesToDisplay = new List<EdAnimationCurve>();
  562. if (selectedFields.Count == 0) // Display all if nothing is selected
  563. {
  564. if (clipInfo == null)
  565. return curvesToDisplay.ToArray();
  566. foreach (var curve in clipInfo.curves)
  567. {
  568. for (int i = 0; i < curve.Value.curves.Length; i++)
  569. curvesToDisplay.Add(curve.Value.curves[i]);
  570. }
  571. }
  572. else
  573. {
  574. for (int i = 0; i < selectedFields.Count; i++)
  575. {
  576. EdAnimationCurve curve;
  577. if (TryGetCurve(selectedFields[i], out curve))
  578. curvesToDisplay.Add(curve);
  579. }
  580. }
  581. return curvesToDisplay.ToArray();
  582. }
  583. private Vector2 GetOptimalRange()
  584. {
  585. EdAnimationCurve[] curvesToDisplay = GetDisplayedCurves();
  586. float xRange;
  587. float yRange;
  588. CalculateRange(curvesToDisplay, out xRange, out yRange);
  589. // Add padding to y range
  590. yRange *= 1.05f;
  591. // Don't allow zero range
  592. if (xRange == 0.0f)
  593. xRange = 60.0f;
  594. if (yRange == 0.0f)
  595. yRange = 10.0f;
  596. return new Vector2(xRange, yRange);
  597. }
  598. private void UpdateDisplayedCurves(bool allowReduce = false)
  599. {
  600. EdAnimationCurve[] curvesToDisplay = GetDisplayedCurves();
  601. guiCurveEditor.SetCurves(curvesToDisplay);
  602. Vector2 newRange = GetOptimalRange();
  603. if (!allowReduce)
  604. {
  605. // Don't reduce visible range
  606. newRange.x = Math.Max(newRange.x, guiCurveEditor.Range.x);
  607. newRange.y = Math.Max(newRange.y, guiCurveEditor.Range.y);
  608. }
  609. guiCurveEditor.Range = newRange;
  610. UpdateScrollBarSize();
  611. }
  612. #endregion
  613. #region Field display
  614. private List<string> selectedFields = new List<string>();
  615. private void AddNewField(string path, SerializableProperty.FieldType type)
  616. {
  617. bool noSelection = selectedFields.Count == 0;
  618. guiFieldDisplay.AddField(new AnimFieldInfo(path, type, !clipInfo.isImported));
  619. switch (type)
  620. {
  621. case SerializableProperty.FieldType.Vector4:
  622. {
  623. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  624. fieldCurves.type = type;
  625. fieldCurves.curves = new EdAnimationCurve[4];
  626. string[] subPaths = { ".x", ".y", ".z", ".w" };
  627. for (int i = 0; i < subPaths.Length; i++)
  628. {
  629. string subFieldPath = path + subPaths[i];
  630. fieldCurves.curves[i] = new EdAnimationCurve();
  631. selectedFields.Add(subFieldPath);
  632. }
  633. clipInfo.curves[path] = fieldCurves;
  634. }
  635. break;
  636. case SerializableProperty.FieldType.Vector3:
  637. {
  638. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  639. fieldCurves.type = type;
  640. fieldCurves.curves = new EdAnimationCurve[3];
  641. string[] subPaths = { ".x", ".y", ".z" };
  642. for (int i = 0; i < subPaths.Length; i++)
  643. {
  644. string subFieldPath = path + subPaths[i];
  645. fieldCurves.curves[i] = new EdAnimationCurve();
  646. selectedFields.Add(subFieldPath);
  647. }
  648. clipInfo.curves[path] = fieldCurves;
  649. }
  650. break;
  651. case SerializableProperty.FieldType.Vector2:
  652. {
  653. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  654. fieldCurves.type = type;
  655. fieldCurves.curves = new EdAnimationCurve[2];
  656. string[] subPaths = { ".x", ".y" };
  657. for (int i = 0; i < subPaths.Length; i++)
  658. {
  659. string subFieldPath = path + subPaths[i];
  660. fieldCurves.curves[i] = new EdAnimationCurve();
  661. selectedFields.Add(subFieldPath);
  662. }
  663. clipInfo.curves[path] = fieldCurves;
  664. }
  665. break;
  666. case SerializableProperty.FieldType.Color:
  667. {
  668. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  669. fieldCurves.type = type;
  670. fieldCurves.curves = new EdAnimationCurve[4];
  671. string[] subPaths = { ".r", ".g", ".b", ".a" };
  672. for (int i = 0; i < subPaths.Length; i++)
  673. {
  674. string subFieldPath = path + subPaths[i];
  675. fieldCurves.curves[i] = new EdAnimationCurve();
  676. selectedFields.Add(subFieldPath);
  677. }
  678. clipInfo.curves[path] = fieldCurves;
  679. }
  680. break;
  681. default: // Primitive type
  682. {
  683. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  684. fieldCurves.type = type;
  685. fieldCurves.curves = new EdAnimationCurve[1];
  686. fieldCurves.curves[0] = new EdAnimationCurve();
  687. selectedFields.Add(path);
  688. clipInfo.curves[path] = fieldCurves;
  689. }
  690. break;
  691. }
  692. EditorApplication.SetProjectDirty();
  693. UpdateDisplayedCurves(noSelection);
  694. }
  695. private void SelectField(string path, bool additive)
  696. {
  697. if (!additive)
  698. selectedFields.Clear();
  699. bool noSelection = selectedFields.Count == 0;
  700. if (!string.IsNullOrEmpty(path))
  701. {
  702. selectedFields.RemoveAll(x => { return x == path || IsPathParent(x, path); });
  703. selectedFields.Add(path);
  704. }
  705. guiFieldDisplay.SetSelection(selectedFields.ToArray());
  706. UpdateDisplayedCurves(noSelection);
  707. }
  708. private void RemoveSelectedFields()
  709. {
  710. for (int i = 0; i < selectedFields.Count; i++)
  711. {
  712. selectedFields.Remove(selectedFields[i]);
  713. clipInfo.curves.Remove(GetSubPathParent(selectedFields[i]));
  714. }
  715. List<AnimFieldInfo> existingFields = new List<AnimFieldInfo>();
  716. foreach (var KVP in clipInfo.curves)
  717. existingFields.Add(new AnimFieldInfo(KVP.Key, KVP.Value.type, !clipInfo.isImported));
  718. guiFieldDisplay.SetFields(existingFields.ToArray());
  719. selectedFields.Clear();
  720. EditorApplication.SetProjectDirty();
  721. UpdateDisplayedCurves();
  722. }
  723. #endregion
  724. #region Helpers
  725. private Vector2I GetCurveEditorSize()
  726. {
  727. Vector2I output = new Vector2I();
  728. output.x = Math.Max(0, Width - FIELD_DISPLAY_WIDTH - scrollBarWidth);
  729. output.y = Math.Max(0, Height - buttonLayoutHeight - scrollBarHeight);
  730. return output;
  731. }
  732. private static void CalculateRange(EdAnimationCurve[] curves, out float xRange, out float yRange)
  733. {
  734. xRange = 0.0f;
  735. yRange = 0.0f;
  736. foreach (var curve in curves)
  737. {
  738. KeyFrame[] keyframes = curve.KeyFrames;
  739. foreach (var key in keyframes)
  740. {
  741. xRange = Math.Max(xRange, key.time);
  742. yRange = Math.Max(yRange, Math.Abs(key.value));
  743. }
  744. }
  745. }
  746. private bool TryGetCurve(string path, out EdAnimationCurve curve)
  747. {
  748. int index = path.LastIndexOf(".");
  749. string parentPath;
  750. string subPathSuffix = null;
  751. if (index == -1)
  752. {
  753. parentPath = path;
  754. }
  755. else
  756. {
  757. parentPath = path.Substring(0, index);
  758. subPathSuffix = path.Substring(index, path.Length - index);
  759. }
  760. FieldAnimCurves fieldCurves;
  761. if (clipInfo.curves.TryGetValue(parentPath, out fieldCurves))
  762. {
  763. if (!string.IsNullOrEmpty(subPathSuffix))
  764. {
  765. if (subPathSuffix == ".x" || subPathSuffix == ".r")
  766. {
  767. curve = fieldCurves.curves[0];
  768. return true;
  769. }
  770. else if (subPathSuffix == ".y" || subPathSuffix == ".g")
  771. {
  772. curve = fieldCurves.curves[1];
  773. return true;
  774. }
  775. else if (subPathSuffix == ".z" || subPathSuffix == ".b")
  776. {
  777. curve = fieldCurves.curves[2];
  778. return true;
  779. }
  780. else if (subPathSuffix == ".w" || subPathSuffix == ".a")
  781. {
  782. curve = fieldCurves.curves[3];
  783. return true;
  784. }
  785. }
  786. else
  787. {
  788. curve = fieldCurves.curves[0];
  789. return true;
  790. }
  791. }
  792. curve = null;
  793. return false;
  794. }
  795. private bool IsPathParent(string child, string parent)
  796. {
  797. string[] childEntries = child.Split('/', '.');
  798. string[] parentEntries = parent.Split('/', '.');
  799. if (parentEntries.Length >= child.Length)
  800. return false;
  801. int compareLength = Math.Min(childEntries.Length, parentEntries.Length);
  802. for (int i = 0; i < compareLength; i++)
  803. {
  804. if (childEntries[i] != parentEntries[i])
  805. return false;
  806. }
  807. return true;
  808. }
  809. private string GetSubPathParent(string path)
  810. {
  811. int index = path.LastIndexOf(".");
  812. if (index == -1)
  813. return path;
  814. return path.Substring(0, index);
  815. }
  816. #endregion
  817. #region Input callbacks
  818. private void OnPointerPressed(PointerEvent ev)
  819. {
  820. guiCurveEditor.OnPointerPressed(ev);
  821. if (ev.button == PointerButton.Middle)
  822. {
  823. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  824. Vector2 curvePos;
  825. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  826. {
  827. dragStartPos = windowPos;
  828. isButtonHeld = true;
  829. }
  830. }
  831. }
  832. private void OnPointerMoved(PointerEvent ev)
  833. {
  834. guiCurveEditor.OnPointerMoved(ev);
  835. if (isButtonHeld)
  836. {
  837. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  838. int distance = Vector2I.Distance(dragStartPos, windowPos);
  839. if (distance >= DRAG_START_DISTANCE)
  840. {
  841. isDragInProgress = true;
  842. Cursor.Hide();
  843. Rect2I clipRect;
  844. clipRect.x = ev.ScreenPos.x - 2;
  845. clipRect.y = ev.ScreenPos.y - 2;
  846. clipRect.width = 4;
  847. clipRect.height = 4;
  848. Cursor.ClipToRect(clipRect);
  849. }
  850. }
  851. }
  852. private void OnPointerReleased(PointerEvent ev)
  853. {
  854. if (isDragInProgress)
  855. {
  856. Cursor.Show();
  857. Cursor.ClipDisable();
  858. }
  859. isButtonHeld = false;
  860. isDragInProgress = false;
  861. guiCurveEditor.OnPointerReleased(ev);
  862. }
  863. private void OnButtonUp(ButtonEvent ev)
  864. {
  865. guiCurveEditor.OnButtonUp(ev);
  866. }
  867. #endregion
  868. #region General callbacks
  869. private void OnFieldAdded(string path, SerializableProperty.FieldType type)
  870. {
  871. // Remove the root scene object from the path (we know which SO it is, no need to hardcode its name in the path)
  872. string pathNoRoot = path.TrimStart('/');
  873. int separatorIdx = pathNoRoot.IndexOf("/");
  874. if (separatorIdx == -1 || (separatorIdx + 1) >= pathNoRoot.Length)
  875. return;
  876. pathNoRoot = pathNoRoot.Substring(separatorIdx + 1, pathNoRoot.Length - separatorIdx - 1);
  877. AddNewField(pathNoRoot, type);
  878. }
  879. private void OnHorzScrollOrResize(float position, float size)
  880. {
  881. SetHorzScrollbarProperties(position, size);
  882. }
  883. private void OnVertScrollOrResize(float position, float size)
  884. {
  885. SetVertScrollbarProperties(position, size);
  886. }
  887. private void OnFieldSelected(string path)
  888. {
  889. bool additive = Input.IsButtonHeld(ButtonCode.LeftShift) || Input.IsButtonHeld(ButtonCode.RightShift);
  890. SelectField(path, additive);
  891. }
  892. private void OnSelectionChanged(SceneObject[] sceneObjects, string[] resourcePaths)
  893. {
  894. UpdateSelectedSO(false);
  895. }
  896. private void OnFrameSelected(int frameIdx)
  897. {
  898. SetCurrentFrame(frameIdx);
  899. }
  900. private void OnEventsChanged()
  901. {
  902. clipInfo.events = guiCurveEditor.Events;
  903. EditorApplication.SetProjectDirty();
  904. }
  905. #endregion
  906. }
  907. /// <summary>
  908. /// Drop down window that displays options used by the animation window.
  909. /// </summary>
  910. [DefaultSize(100, 50)]
  911. internal class AnimationOptions : DropDownWindow
  912. {
  913. /// <summary>
  914. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  915. /// use.
  916. /// </summary>
  917. /// <param name="parent">Animation window that this drop down window is a part of.</param>
  918. internal void Initialize(AnimationWindow parent)
  919. {
  920. GUIIntField fpsField = new GUIIntField(new LocEdString("FPS"), 40);
  921. fpsField.Value = parent.FPS;
  922. fpsField.OnChanged += x => { parent.FPS = x; };
  923. GUILayoutY vertLayout = GUI.AddLayoutY();
  924. vertLayout.AddFlexibleSpace();
  925. GUILayoutX contentLayout = vertLayout.AddLayoutX();
  926. contentLayout.AddFlexibleSpace();
  927. contentLayout.AddElement(fpsField);
  928. contentLayout.AddFlexibleSpace();
  929. vertLayout.AddFlexibleSpace();
  930. }
  931. }
  932. /** @} */
  933. }