AnimationWindow.cs 41 KB

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