AnimationWindow.cs 40 KB

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