AnimationWindow.cs 41 KB

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