AnimationWindow.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  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 = 200;
  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 (IsClipImported(clipInfo.clip))
  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 (IsClipImported(clipInfo.clip))
  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. bool clipIsImported = IsClipImported(clip);
  431. if (persistentData.dirtyAnimClips.TryGetValue(clip.UUID, out clipInfo))
  432. {
  433. // If an animation clip is imported, we don't care about it's cached curve values as they could have changed
  434. // since last modification, so we re-load the clip. But we persist the events as those can only be set
  435. // within the editor.
  436. if (clipIsImported)
  437. {
  438. EditorAnimClipInfo newClipInfo = EditorAnimClipInfo.Create(clip);
  439. newClipInfo.events = clipInfo.events;
  440. }
  441. }
  442. else
  443. clipInfo = EditorAnimClipInfo.Create(clip);
  444. persistentData.dirtyAnimClips[clip.UUID] = clipInfo;
  445. foreach (var curve in clipInfo.curves)
  446. guiFieldDisplay.AddField(curve.Key);
  447. guiCurveEditor.Events = clipInfo.events;
  448. guiCurveEditor.DisableCurveEdit = clipIsImported;
  449. SetCurrentFrame(0);
  450. }
  451. private static bool IsClipImported(AnimationClip clip)
  452. {
  453. string resourcePath = ProjectLibrary.GetPath(clip);
  454. return ProjectLibrary.IsSubresource(resourcePath);
  455. }
  456. private void UpdateSelectedSO(bool force)
  457. {
  458. SceneObject so = Selection.SceneObject;
  459. if (selectedSO != so || force)
  460. {
  461. if (selectedSO != null && so == null)
  462. {
  463. EditorInput.OnPointerPressed -= OnPointerPressed;
  464. EditorInput.OnPointerMoved -= OnPointerMoved;
  465. EditorInput.OnPointerReleased -= OnPointerReleased;
  466. EditorInput.OnButtonUp -= OnButtonUp;
  467. }
  468. else if (selectedSO == null && so != null)
  469. {
  470. EditorInput.OnPointerPressed += OnPointerPressed;
  471. EditorInput.OnPointerMoved += OnPointerMoved;
  472. EditorInput.OnPointerReleased += OnPointerReleased;
  473. EditorInput.OnButtonUp += OnButtonUp;
  474. }
  475. zoomAmount = 0.0f;
  476. selectedSO = so;
  477. selectedFields.Clear();
  478. clipInfo = null;
  479. RebuildGUI();
  480. // Load existing clip if one exists
  481. if (selectedSO != null)
  482. {
  483. Animation animation = selectedSO.GetComponent<Animation>();
  484. if (animation != null)
  485. {
  486. AnimationClip clip = animation.DefaultClip;
  487. if (clip != null)
  488. LoadAnimClip(clip);
  489. }
  490. }
  491. if(clipInfo == null)
  492. clipInfo = new EditorAnimClipInfo();
  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. string suffix;
  514. SerializableProperty property = Animation.FindProperty(selectedSO, kvp.Key, out suffix);
  515. if (property != null)
  516. {
  517. GUIAnimFieldPathValue fieldValue = new GUIAnimFieldPathValue();
  518. fieldValue.path = kvp.Key;
  519. switch (kvp.Value.type)
  520. {
  521. case SerializableProperty.FieldType.Vector2:
  522. {
  523. Vector2 value = new Vector2();
  524. for (int i = 0; i < 2; i++)
  525. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  526. fieldValue.value = value;
  527. }
  528. break;
  529. case SerializableProperty.FieldType.Vector3:
  530. {
  531. Vector3 value = new Vector3();
  532. for (int i = 0; i < 3; i++)
  533. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  534. fieldValue.value = value;
  535. }
  536. break;
  537. case SerializableProperty.FieldType.Vector4:
  538. {
  539. Vector4 value = new Vector4();
  540. for (int i = 0; i < 4; i++)
  541. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  542. fieldValue.value = value;
  543. }
  544. break;
  545. case SerializableProperty.FieldType.Color:
  546. {
  547. Color value = new Color();
  548. for (int i = 0; i < 4; i++)
  549. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  550. fieldValue.value = value;
  551. }
  552. break;
  553. case SerializableProperty.FieldType.Bool:
  554. case SerializableProperty.FieldType.Int:
  555. case SerializableProperty.FieldType.Float:
  556. fieldValue.value = kvp.Value.curves[0].Evaluate(time, false); ;
  557. break;
  558. }
  559. values.Add(fieldValue);
  560. }
  561. }
  562. guiFieldDisplay.SetDisplayValues(values.ToArray());
  563. }
  564. private Vector2 GetOptimalRange()
  565. {
  566. List<EdAnimationCurve> displayedCurves = new List<EdAnimationCurve>();
  567. for (int i = 0; i < selectedFields.Count; i++)
  568. {
  569. EdAnimationCurve curve;
  570. if (TryGetCurve(selectedFields[i], out curve))
  571. displayedCurves.Add(curve);
  572. }
  573. float xRange;
  574. float yRange;
  575. CalculateRange(displayedCurves, out xRange, out yRange);
  576. // Add padding to y range
  577. yRange *= 1.05f;
  578. // Don't allow zero range
  579. if (xRange == 0.0f)
  580. xRange = 60.0f;
  581. if (yRange == 0.0f)
  582. yRange = 10.0f;
  583. return new Vector2(xRange, yRange);
  584. }
  585. private void UpdateDisplayedCurves(bool allowReduce = false)
  586. {
  587. List<EdAnimationCurve> curvesToDisplay = new List<EdAnimationCurve>();
  588. for (int i = 0; i < selectedFields.Count; i++)
  589. {
  590. EdAnimationCurve curve;
  591. if (TryGetCurve(selectedFields[i], out curve))
  592. curvesToDisplay.Add(curve);
  593. }
  594. guiCurveEditor.SetCurves(curvesToDisplay.ToArray());
  595. Vector2 newRange = GetOptimalRange();
  596. if (!allowReduce)
  597. {
  598. // Don't reduce visible range
  599. newRange.x = Math.Max(newRange.x, guiCurveEditor.Range.x);
  600. newRange.y = Math.Max(newRange.y, guiCurveEditor.Range.y);
  601. }
  602. guiCurveEditor.Range = newRange;
  603. UpdateScrollBarSize();
  604. }
  605. #endregion
  606. #region Field display
  607. private List<string> selectedFields = new List<string>();
  608. private void AddNewField(string path, SerializableProperty.FieldType type)
  609. {
  610. bool noSelection = selectedFields.Count == 0;
  611. guiFieldDisplay.AddField(path);
  612. switch (type)
  613. {
  614. case SerializableProperty.FieldType.Vector4:
  615. {
  616. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  617. fieldCurves.type = type;
  618. fieldCurves.curves = new EdAnimationCurve[4];
  619. string[] subPaths = { ".x", ".y", ".z", ".w" };
  620. for (int i = 0; i < subPaths.Length; i++)
  621. {
  622. string subFieldPath = path + subPaths[i];
  623. fieldCurves.curves[i] = new EdAnimationCurve();
  624. selectedFields.Add(subFieldPath);
  625. }
  626. clipInfo.curves[path] = fieldCurves;
  627. }
  628. break;
  629. case SerializableProperty.FieldType.Vector3:
  630. {
  631. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  632. fieldCurves.type = type;
  633. fieldCurves.curves = new EdAnimationCurve[3];
  634. string[] subPaths = { ".x", ".y", ".z" };
  635. for (int i = 0; i < subPaths.Length; i++)
  636. {
  637. string subFieldPath = path + subPaths[i];
  638. fieldCurves.curves[i] = new EdAnimationCurve();
  639. selectedFields.Add(subFieldPath);
  640. }
  641. clipInfo.curves[path] = fieldCurves;
  642. }
  643. break;
  644. case SerializableProperty.FieldType.Vector2:
  645. {
  646. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  647. fieldCurves.type = type;
  648. fieldCurves.curves = new EdAnimationCurve[2];
  649. string[] subPaths = { ".x", ".y" };
  650. for (int i = 0; i < subPaths.Length; i++)
  651. {
  652. string subFieldPath = path + subPaths[i];
  653. fieldCurves.curves[i] = new EdAnimationCurve();
  654. selectedFields.Add(subFieldPath);
  655. }
  656. clipInfo.curves[path] = fieldCurves;
  657. }
  658. break;
  659. case SerializableProperty.FieldType.Color:
  660. {
  661. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  662. fieldCurves.type = type;
  663. fieldCurves.curves = new EdAnimationCurve[4];
  664. string[] subPaths = { ".r", ".g", ".b", ".a" };
  665. for (int i = 0; i < subPaths.Length; i++)
  666. {
  667. string subFieldPath = path + subPaths[i];
  668. fieldCurves.curves[i] = new EdAnimationCurve();
  669. selectedFields.Add(subFieldPath);
  670. }
  671. clipInfo.curves[path] = fieldCurves;
  672. }
  673. break;
  674. default: // Primitive type
  675. {
  676. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  677. fieldCurves.type = type;
  678. fieldCurves.curves = new EdAnimationCurve[1];
  679. fieldCurves.curves[0] = new EdAnimationCurve();
  680. selectedFields.Add(path);
  681. clipInfo.curves[path] = fieldCurves;
  682. }
  683. break;
  684. }
  685. EditorApplication.SetProjectDirty();
  686. UpdateDisplayedCurves(noSelection);
  687. }
  688. private void SelectField(string path, bool additive)
  689. {
  690. if (!additive)
  691. selectedFields.Clear();
  692. bool noSelection = selectedFields.Count == 0;
  693. if (!string.IsNullOrEmpty(path))
  694. {
  695. selectedFields.RemoveAll(x => { return x == path || IsPathParent(x, path); });
  696. selectedFields.Add(path);
  697. }
  698. guiFieldDisplay.SetSelection(selectedFields.ToArray());
  699. UpdateDisplayedCurves(noSelection);
  700. }
  701. private void RemoveSelectedFields()
  702. {
  703. for (int i = 0; i < selectedFields.Count; i++)
  704. {
  705. selectedFields.Remove(selectedFields[i]);
  706. clipInfo.curves.Remove(GetSubPathParent(selectedFields[i]));
  707. }
  708. List<string> existingFields = new List<string>();
  709. foreach (var KVP in clipInfo.curves)
  710. existingFields.Add(KVP.Key);
  711. guiFieldDisplay.SetFields(existingFields.ToArray());
  712. selectedFields.Clear();
  713. EditorApplication.SetProjectDirty();
  714. UpdateDisplayedCurves();
  715. }
  716. #endregion
  717. #region Helpers
  718. private Vector2I GetCurveEditorSize()
  719. {
  720. Vector2I output = new Vector2I();
  721. output.x = Math.Max(0, Width - FIELD_DISPLAY_WIDTH - scrollBarWidth);
  722. output.y = Math.Max(0, Height - buttonLayoutHeight - scrollBarHeight);
  723. return output;
  724. }
  725. private static void CalculateRange(List<EdAnimationCurve> curves, out float xRange, out float yRange)
  726. {
  727. xRange = 0.0f;
  728. yRange = 0.0f;
  729. foreach (var curve in curves)
  730. {
  731. KeyFrame[] keyframes = curve.KeyFrames;
  732. foreach (var key in keyframes)
  733. {
  734. xRange = Math.Max(xRange, key.time);
  735. yRange = Math.Max(yRange, Math.Abs(key.value));
  736. }
  737. }
  738. }
  739. private bool TryGetCurve(string path, out EdAnimationCurve curve)
  740. {
  741. int index = path.LastIndexOf(".");
  742. string parentPath;
  743. string subPathSuffix = null;
  744. if (index == -1)
  745. {
  746. parentPath = path;
  747. }
  748. else
  749. {
  750. parentPath = path.Substring(0, index);
  751. subPathSuffix = path.Substring(index, path.Length - index);
  752. }
  753. FieldAnimCurves fieldCurves;
  754. if (clipInfo.curves.TryGetValue(parentPath, out fieldCurves))
  755. {
  756. if (!string.IsNullOrEmpty(subPathSuffix))
  757. {
  758. if (subPathSuffix == ".x" || subPathSuffix == ".r")
  759. {
  760. curve = fieldCurves.curves[0];
  761. return true;
  762. }
  763. else if (subPathSuffix == ".y" || subPathSuffix == ".g")
  764. {
  765. curve = fieldCurves.curves[1];
  766. return true;
  767. }
  768. else if (subPathSuffix == ".z" || subPathSuffix == ".b")
  769. {
  770. curve = fieldCurves.curves[2];
  771. return true;
  772. }
  773. else if (subPathSuffix == ".w" || subPathSuffix == ".a")
  774. {
  775. curve = fieldCurves.curves[3];
  776. return true;
  777. }
  778. }
  779. else
  780. {
  781. curve = fieldCurves.curves[0];
  782. return true;
  783. }
  784. }
  785. curve = null;
  786. return false;
  787. }
  788. private bool IsPathParent(string child, string parent)
  789. {
  790. string[] childEntries = child.Split('/', '.');
  791. string[] parentEntries = parent.Split('/', '.');
  792. if (parentEntries.Length >= child.Length)
  793. return false;
  794. int compareLength = Math.Min(childEntries.Length, parentEntries.Length);
  795. for (int i = 0; i < compareLength; i++)
  796. {
  797. if (childEntries[i] != parentEntries[i])
  798. return false;
  799. }
  800. return true;
  801. }
  802. private string GetSubPathParent(string path)
  803. {
  804. int index = path.LastIndexOf(".");
  805. if (index == -1)
  806. return path;
  807. return path.Substring(0, index);
  808. }
  809. #endregion
  810. #region Input callbacks
  811. private void OnPointerPressed(PointerEvent ev)
  812. {
  813. guiCurveEditor.OnPointerPressed(ev);
  814. if (ev.button == PointerButton.Middle)
  815. {
  816. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  817. Vector2 curvePos;
  818. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  819. {
  820. dragStartPos = windowPos;
  821. isButtonHeld = true;
  822. }
  823. }
  824. }
  825. private void OnPointerMoved(PointerEvent ev)
  826. {
  827. guiCurveEditor.OnPointerMoved(ev);
  828. if (isButtonHeld)
  829. {
  830. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  831. int distance = Vector2I.Distance(dragStartPos, windowPos);
  832. if (distance >= DRAG_START_DISTANCE)
  833. {
  834. isDragInProgress = true;
  835. Cursor.Hide();
  836. Rect2I clipRect;
  837. clipRect.x = ev.ScreenPos.x - 2;
  838. clipRect.y = ev.ScreenPos.y - 2;
  839. clipRect.width = 4;
  840. clipRect.height = 4;
  841. Cursor.ClipToRect(clipRect);
  842. }
  843. }
  844. }
  845. private void OnPointerReleased(PointerEvent ev)
  846. {
  847. if (isDragInProgress)
  848. {
  849. Cursor.Show();
  850. Cursor.ClipDisable();
  851. }
  852. isButtonHeld = false;
  853. isDragInProgress = false;
  854. guiCurveEditor.OnPointerReleased(ev);
  855. }
  856. private void OnButtonUp(ButtonEvent ev)
  857. {
  858. guiCurveEditor.OnButtonUp(ev);
  859. }
  860. #endregion
  861. #region General callbacks
  862. private void OnFieldAdded(string path, SerializableProperty.FieldType type)
  863. {
  864. // Remove the root scene object from the path (we know which SO it is, no need to hardcode its name in the path)
  865. string pathNoRoot = path.TrimStart('/');
  866. int separatorIdx = pathNoRoot.IndexOf("/");
  867. if (separatorIdx == -1 || (separatorIdx + 1) >= pathNoRoot.Length)
  868. return;
  869. pathNoRoot = pathNoRoot.Substring(separatorIdx + 1, pathNoRoot.Length - separatorIdx - 1);
  870. AddNewField(pathNoRoot, type);
  871. }
  872. private void OnHorzScrollOrResize(float position, float size)
  873. {
  874. SetHorzScrollbarProperties(position, size);
  875. }
  876. private void OnVertScrollOrResize(float position, float size)
  877. {
  878. SetVertScrollbarProperties(position, size);
  879. }
  880. private void OnFieldSelected(string path)
  881. {
  882. bool additive = Input.IsButtonHeld(ButtonCode.LeftShift) || Input.IsButtonHeld(ButtonCode.RightShift);
  883. SelectField(path, additive);
  884. }
  885. private void OnSelectionChanged(SceneObject[] sceneObjects, string[] resourcePaths)
  886. {
  887. UpdateSelectedSO(false);
  888. }
  889. private void OnFrameSelected(int frameIdx)
  890. {
  891. SetCurrentFrame(frameIdx);
  892. }
  893. private void OnEventsChanged()
  894. {
  895. clipInfo.events = guiCurveEditor.Events;
  896. EditorApplication.SetProjectDirty();
  897. }
  898. #endregion
  899. }
  900. /// <summary>
  901. /// Drop down window that displays options used by the animation window.
  902. /// </summary>
  903. [DefaultSize(100, 50)]
  904. internal class AnimationOptions : DropDownWindow
  905. {
  906. /// <summary>
  907. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  908. /// use.
  909. /// </summary>
  910. /// <param name="parent">Animation window that this drop down window is a part of.</param>
  911. internal void Initialize(AnimationWindow parent)
  912. {
  913. GUIIntField fpsField = new GUIIntField(new LocEdString("FPS"), 40);
  914. fpsField.Value = parent.FPS;
  915. fpsField.OnChanged += x => { parent.FPS = x; };
  916. GUILayoutY vertLayout = GUI.AddLayoutY();
  917. vertLayout.AddFlexibleSpace();
  918. GUILayoutX contentLayout = vertLayout.AddLayoutX();
  919. contentLayout.AddFlexibleSpace();
  920. contentLayout.AddElement(fpsField);
  921. contentLayout.AddFlexibleSpace();
  922. vertLayout.AddFlexibleSpace();
  923. }
  924. }
  925. /** @} */
  926. }