2
0

AnimationWindow.cs 42 KB

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