AnimationWindow.cs 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  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. Allows the user to manipulate keyframes of animation curves, add/remove
  15. /// curves from an animation clip, and manipulate animation events.
  16. /// </summary>
  17. [DefaultSize(900, 500)]
  18. internal class AnimationWindow : EditorWindow
  19. {
  20. private const int FIELD_DISPLAY_WIDTH = 300;
  21. private const int DRAG_START_DISTANCE = 3;
  22. private const float DRAG_SCALE = 3.0f;
  23. private const float ZOOM_SCALE = 0.1f/120.0f; // One scroll step is usually 120 units, we want 1/10 of that
  24. private SceneObject selectedSO;
  25. /// <summary>
  26. /// Scene object for which are we currently changing the animation for.
  27. /// </summary>
  28. internal SceneObject SelectedSO
  29. {
  30. get { return selectedSO; }
  31. }
  32. #region Overrides
  33. /// <summary>
  34. /// Opens the animation window.
  35. /// </summary>
  36. [MenuItem("Windows/Animation", ButtonModifier.CtrlAlt, ButtonCode.A, 6000)]
  37. private static void OpenGameWindow()
  38. {
  39. OpenWindow<AnimationWindow>();
  40. }
  41. /// <inheritdoc/>
  42. protected override LocString GetDisplayName()
  43. {
  44. return new LocEdString("Animation");
  45. }
  46. private void OnInitialize()
  47. {
  48. Selection.OnSelectionChanged += OnSelectionChanged;
  49. UpdateSelectedSO(true);
  50. }
  51. private void OnEditorUpdate()
  52. {
  53. if (selectedSO == null)
  54. return;
  55. HandleDragAndZoomInput();
  56. }
  57. private void OnDestroy()
  58. {
  59. Selection.OnSelectionChanged -= OnSelectionChanged;
  60. if (selectedSO != null)
  61. {
  62. EditorInput.OnPointerPressed -= OnPointerPressed;
  63. EditorInput.OnPointerMoved -= OnPointerMoved;
  64. EditorInput.OnPointerReleased -= OnPointerReleased;
  65. EditorInput.OnButtonUp -= OnButtonUp;
  66. }
  67. }
  68. /// <inheritdoc/>
  69. protected override void WindowResized(int width, int height)
  70. {
  71. if (selectedSO == null)
  72. return;
  73. ResizeGUI(width, height);
  74. }
  75. #endregion
  76. #region GUI
  77. private GUIButton playButton;
  78. private GUIButton recordButton;
  79. private GUIButton prevFrameButton;
  80. private GUIIntField frameInputField;
  81. private GUIButton nextFrameButton;
  82. private GUIButton addKeyframeButton;
  83. private GUIButton addEventButton;
  84. private GUIButton optionsButton;
  85. private GUIButton addPropertyBtn;
  86. private GUIButton delPropertyBtn;
  87. private GUILayout buttonLayout;
  88. private int buttonLayoutHeight;
  89. private int scrollBarWidth;
  90. private int scrollBarHeight;
  91. private GUIResizeableScrollBarH horzScrollBar;
  92. private GUIResizeableScrollBarV vertScrollBar;
  93. private GUIPanel editorPanel;
  94. private GUIAnimFieldDisplay guiFieldDisplay;
  95. private GUICurveEditor guiCurveEditor;
  96. /// <summary>
  97. /// Recreates the entire curve editor GUI depending on the currently selected scene object.
  98. /// </summary>
  99. private void RebuildGUI()
  100. {
  101. GUI.Clear();
  102. guiCurveEditor = null;
  103. guiFieldDisplay = null;
  104. if (selectedSO == null)
  105. {
  106. GUILabel warningLbl = new GUILabel(new LocEdString("Select an object to animate in the Hierarchy or Scene windows."));
  107. GUILayoutY vertLayout = GUI.AddLayoutY();
  108. vertLayout.AddFlexibleSpace();
  109. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  110. vertLayout.AddFlexibleSpace();
  111. horzLayout.AddFlexibleSpace();
  112. horzLayout.AddElement(warningLbl);
  113. horzLayout.AddFlexibleSpace();
  114. return;
  115. }
  116. // Top button row
  117. GUIContent playIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Play),
  118. new LocEdString("Play"));
  119. GUIContent recordIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Record),
  120. new LocEdString("Record"));
  121. GUIContent prevFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameBack),
  122. new LocEdString("Previous frame"));
  123. GUIContent nextFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameForward),
  124. new LocEdString("Next frame"));
  125. GUIContent addKeyframeIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddKeyframe),
  126. new LocEdString("Add keyframe"));
  127. GUIContent addEventIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddEvent),
  128. new LocEdString("Add event"));
  129. GUIContent optionsIcon = new GUIContent(EditorBuiltin.GetLibraryWindowIcon(LibraryWindowIcon.Options),
  130. new LocEdString("Options"));
  131. playButton = new GUIButton(playIcon);
  132. recordButton = new GUIButton(recordIcon);
  133. prevFrameButton = new GUIButton(prevFrameIcon);
  134. frameInputField = new GUIIntField();
  135. nextFrameButton = new GUIButton(nextFrameIcon);
  136. addKeyframeButton = new GUIButton(addKeyframeIcon);
  137. addEventButton = new GUIButton(addEventIcon);
  138. optionsButton = new GUIButton(optionsIcon);
  139. playButton.OnClick += () =>
  140. {
  141. // TODO
  142. // - Record current state of the scene object hierarchy
  143. // - Evaluate all curves manually and update them
  144. // - On end, restore original values of the scene object hierarchy
  145. };
  146. recordButton.OnClick += () =>
  147. {
  148. // TODO
  149. // - Every frame read back current values of all the current curve's properties and assign it to the current frame
  150. };
  151. prevFrameButton.OnClick += () =>
  152. {
  153. SetCurrentFrame(currentFrameIdx - 1);
  154. };
  155. frameInputField.OnChanged += SetCurrentFrame;
  156. nextFrameButton.OnClick += () =>
  157. {
  158. SetCurrentFrame(currentFrameIdx + 1);
  159. };
  160. addKeyframeButton.OnClick += () =>
  161. {
  162. guiCurveEditor.AddKeyFrameAtMarker();
  163. };
  164. addEventButton.OnClick += () =>
  165. {
  166. guiCurveEditor.AddEventAtMarker();
  167. };
  168. optionsButton.OnClick += () =>
  169. {
  170. Vector2I openPosition = ScreenToWindowPos(Input.PointerPosition);
  171. AnimationOptions dropDown = DropDownWindow.Open<AnimationOptions>(this, openPosition);
  172. dropDown.Initialize(this);
  173. };
  174. // Property buttons
  175. addPropertyBtn = new GUIButton(new LocEdString("Add property"));
  176. delPropertyBtn = new GUIButton(new LocEdString("Delete selected"));
  177. addPropertyBtn.OnClick += () =>
  178. {
  179. Action openPropertyWindow = () =>
  180. {
  181. Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
  182. FieldSelectionWindow fieldSelection = DropDownWindow.Open<FieldSelectionWindow>(this, windowPos);
  183. fieldSelection.OnFieldSelected += OnFieldAdded;
  184. };
  185. if (clipInfo.clip == null)
  186. {
  187. LocEdString title = new LocEdString("Warning");
  188. LocEdString message =
  189. new LocEdString("Selected object doesn't have an animation clip assigned. Would you like to create" +
  190. " a new animation clip?");
  191. DialogBox.Open(title, message, DialogBox.Type.YesNoCancel, type =>
  192. {
  193. if (type == DialogBox.ResultType.Yes)
  194. {
  195. string clipSavePath;
  196. if (BrowseDialog.SaveFile(ProjectLibrary.ResourceFolder, "*.asset", out clipSavePath))
  197. {
  198. clipSavePath = Path.ChangeExtension(clipSavePath, ".asset");
  199. AnimationClip newClip = new AnimationClip();
  200. ProjectLibrary.Create(newClip, clipSavePath);
  201. LoadAnimClip(newClip);
  202. Animation animation = selectedSO.GetComponent<Animation>();
  203. if (animation == null)
  204. animation = selectedSO.AddComponent<Animation>();
  205. animation.DefaultClip = newClip;
  206. EditorApplication.SetSceneDirty();
  207. openPropertyWindow();
  208. }
  209. }
  210. });
  211. }
  212. else
  213. {
  214. if (clipInfo.isImported)
  215. {
  216. LocEdString title = new LocEdString("Warning");
  217. LocEdString message =
  218. new LocEdString("You cannot add/edit/remove curves from animation clips that" +
  219. " are imported from an external file.");
  220. DialogBox.Open(title, message, DialogBox.Type.OK);
  221. }
  222. else
  223. openPropertyWindow();
  224. }
  225. };
  226. delPropertyBtn.OnClick += () =>
  227. {
  228. if (clipInfo.clip == null)
  229. return;
  230. if (clipInfo.isImported)
  231. {
  232. LocEdString title = new LocEdString("Warning");
  233. LocEdString message =
  234. new LocEdString("You cannot add/edit/remove curves from animation clips that" +
  235. " are imported from an external file.");
  236. DialogBox.Open(title, message, DialogBox.Type.OK);
  237. }
  238. else
  239. {
  240. LocEdString title = new LocEdString("Warning");
  241. LocEdString message = new LocEdString("Are you sure you want to remove all selected fields?");
  242. DialogBox.Open(title, message, DialogBox.Type.YesNo, x =>
  243. {
  244. if (x == DialogBox.ResultType.Yes)
  245. {
  246. RemoveSelectedFields();
  247. }
  248. });
  249. }
  250. };
  251. GUIPanel mainPanel = GUI.AddPanel();
  252. GUIPanel backgroundPanel = GUI.AddPanel(1);
  253. GUILayout mainLayout = mainPanel.AddLayoutY();
  254. buttonLayout = mainLayout.AddLayoutX();
  255. buttonLayout.AddSpace(5);
  256. buttonLayout.AddElement(playButton);
  257. buttonLayout.AddElement(recordButton);
  258. buttonLayout.AddSpace(5);
  259. buttonLayout.AddElement(prevFrameButton);
  260. buttonLayout.AddElement(frameInputField);
  261. buttonLayout.AddElement(nextFrameButton);
  262. buttonLayout.AddSpace(5);
  263. buttonLayout.AddElement(addKeyframeButton);
  264. buttonLayout.AddElement(addEventButton);
  265. buttonLayout.AddSpace(5);
  266. buttonLayout.AddElement(optionsButton);
  267. buttonLayout.AddFlexibleSpace();
  268. buttonLayoutHeight = playButton.Bounds.height;
  269. GUITexture buttonBackground = new GUITexture(null, EditorStyles.HeaderBackground);
  270. buttonBackground.Bounds = new Rect2I(0, 0, Width, buttonLayoutHeight);
  271. backgroundPanel.AddElement(buttonBackground);
  272. GUILayout contentLayout = mainLayout.AddLayoutX();
  273. GUILayout fieldDisplayLayout = contentLayout.AddLayoutY(GUIOption.FixedWidth(FIELD_DISPLAY_WIDTH));
  274. guiFieldDisplay = new GUIAnimFieldDisplay(fieldDisplayLayout, FIELD_DISPLAY_WIDTH,
  275. Height - buttonLayoutHeight * 2, selectedSO);
  276. guiFieldDisplay.OnEntrySelected += OnFieldSelected;
  277. GUILayout bottomButtonLayout = fieldDisplayLayout.AddLayoutX();
  278. bottomButtonLayout.AddElement(addPropertyBtn);
  279. bottomButtonLayout.AddElement(delPropertyBtn);
  280. horzScrollBar = new GUIResizeableScrollBarH();
  281. horzScrollBar.OnScrollOrResize += OnHorzScrollOrResize;
  282. vertScrollBar = new GUIResizeableScrollBarV();
  283. vertScrollBar.OnScrollOrResize += OnVertScrollOrResize;
  284. GUITexture separator = new GUITexture(null, EditorStyles.Separator, GUIOption.FixedWidth(3));
  285. contentLayout.AddElement(separator);
  286. GUILayout curveLayout = contentLayout.AddLayoutY();
  287. GUILayout curveLayoutHorz = curveLayout.AddLayoutX();
  288. GUILayout horzScrollBarLayout = curveLayout.AddLayoutX();
  289. horzScrollBarLayout.AddElement(horzScrollBar);
  290. horzScrollBarLayout.AddFlexibleSpace();
  291. editorPanel = curveLayoutHorz.AddPanel();
  292. curveLayoutHorz.AddElement(vertScrollBar);
  293. curveLayoutHorz.AddFlexibleSpace();
  294. scrollBarHeight = horzScrollBar.Bounds.height;
  295. scrollBarWidth = vertScrollBar.Bounds.width;
  296. Vector2I curveEditorSize = GetCurveEditorSize();
  297. guiCurveEditor = new GUICurveEditor(this, editorPanel, curveEditorSize.x, curveEditorSize.y);
  298. guiCurveEditor.OnFrameSelected += OnFrameSelected;
  299. guiCurveEditor.OnEventAdded += OnEventsChanged;
  300. guiCurveEditor.OnEventModified += EditorApplication.SetProjectDirty;
  301. guiCurveEditor.OnEventDeleted += OnEventsChanged;
  302. guiCurveEditor.OnCurveModified += EditorApplication.SetProjectDirty;
  303. guiCurveEditor.Redraw();
  304. horzScrollBar.SetWidth(curveEditorSize.x);
  305. vertScrollBar.SetHeight(curveEditorSize.y);
  306. UpdateScrollBarSize();
  307. }
  308. /// <summary>
  309. /// Resizes GUI elements so they fit within the provided boundaries.
  310. /// </summary>
  311. /// <param name="width">Width of the GUI bounds, in pixels.</param>
  312. /// <param name="height">Height of the GUI bounds, in pixels.</param>
  313. private void ResizeGUI(int width, int height)
  314. {
  315. guiFieldDisplay.SetSize(FIELD_DISPLAY_WIDTH, height - buttonLayoutHeight * 2);
  316. Vector2I curveEditorSize = GetCurveEditorSize();
  317. guiCurveEditor.SetSize(curveEditorSize.x, curveEditorSize.y);
  318. guiCurveEditor.Redraw();
  319. horzScrollBar.SetWidth(curveEditorSize.x);
  320. vertScrollBar.SetHeight(curveEditorSize.y);
  321. UpdateScrollBarSize();
  322. UpdateScrollBarPosition();
  323. }
  324. #endregion
  325. #region Scroll, drag, zoom
  326. private Vector2I dragStartPos;
  327. private bool isButtonHeld;
  328. private bool isDragInProgress;
  329. private float zoomAmount;
  330. /// <summary>
  331. /// Handles mouse scroll wheel and dragging events in order to zoom or drag the displayed curve editor contents.
  332. /// </summary>
  333. private void HandleDragAndZoomInput()
  334. {
  335. // Handle middle mouse dragging
  336. if (isDragInProgress)
  337. {
  338. float lengthPerPixel = guiCurveEditor.Range.x / guiCurveEditor.Width;
  339. float heightPerPixel = guiCurveEditor.Range.y / guiCurveEditor.Height;
  340. float dragX = Input.GetAxisValue(InputAxis.MouseX) * DRAG_SCALE * lengthPerPixel;
  341. float dragY = Input.GetAxisValue(InputAxis.MouseY) * DRAG_SCALE * heightPerPixel;
  342. Vector2 offset = guiCurveEditor.Offset;
  343. offset.x = Math.Max(0.0f, offset.x + dragX);
  344. offset.y -= dragY;
  345. guiCurveEditor.Offset = offset;
  346. UpdateScrollBarSize();
  347. UpdateScrollBarPosition();
  348. }
  349. // Handle zoom in/out
  350. float scroll = Input.GetAxisValue(InputAxis.MouseZ);
  351. if (scroll != 0.0f)
  352. {
  353. Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
  354. Vector2 curvePos;
  355. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  356. {
  357. float zoom = scroll * ZOOM_SCALE;
  358. Zoom(curvePos, zoom);
  359. }
  360. }
  361. }
  362. /// <summary>
  363. /// Moves or resizes the vertical scroll bar under the curve editor.
  364. /// </summary>
  365. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  366. /// <param name="size">New size of the scrollbar handle, in range [0, 1].</param>
  367. private void SetVertScrollbarProperties(float position, float size)
  368. {
  369. Vector2 visibleRange = guiCurveEditor.Range;
  370. Vector2 totalRange = GetTotalRange();
  371. visibleRange.y = totalRange.y*size;
  372. guiCurveEditor.Range = visibleRange;
  373. float scrollableRange = totalRange.y - visibleRange.y;
  374. Vector2 offset = guiCurveEditor.Offset;
  375. offset.y = -scrollableRange * (position * 2.0f - 1.0f);
  376. guiCurveEditor.Offset = offset;
  377. }
  378. /// <summary>
  379. /// Moves or resizes the horizontal scroll bar under the curve editor.
  380. /// </summary>
  381. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  382. /// <param name="size">New size of the scrollbar handle, in range [0, 1].</param>
  383. private void SetHorzScrollbarProperties(float position, float size)
  384. {
  385. Vector2 visibleRange = guiCurveEditor.Range;
  386. Vector2 totalRange = GetTotalRange();
  387. visibleRange.x = totalRange.x * size;
  388. guiCurveEditor.Range = visibleRange;
  389. float scrollableRange = totalRange.x - visibleRange.x;
  390. Vector2 offset = guiCurveEditor.Offset;
  391. offset.x = scrollableRange * position;
  392. guiCurveEditor.Offset = offset;
  393. }
  394. /// <summary>
  395. /// Updates the size of both scrollbars depending on the currently visible curve area vs. the total curve area.
  396. /// </summary>
  397. private void UpdateScrollBarSize()
  398. {
  399. Vector2 visibleRange = guiCurveEditor.Range;
  400. Vector2 totalRange = GetTotalRange();
  401. horzScrollBar.HandleSize = visibleRange.x / totalRange.x;
  402. vertScrollBar.HandleSize = visibleRange.y / totalRange.y;
  403. }
  404. /// <summary>
  405. /// Updates the position of both scrollbars depending on the offset currently applied to the visible curve area.
  406. /// </summary>
  407. private void UpdateScrollBarPosition()
  408. {
  409. Vector2 visibleRange = guiCurveEditor.Range;
  410. Vector2 totalRange = GetTotalRange();
  411. Vector2 scrollableRange = totalRange - visibleRange;
  412. Vector2 offset = guiCurveEditor.Offset;
  413. if (scrollableRange.x > 0.0f)
  414. horzScrollBar.Position = offset.x / scrollableRange.x;
  415. else
  416. horzScrollBar.Position = 0.0f;
  417. if (scrollableRange.y > 0.0f)
  418. {
  419. float pos = offset.y/scrollableRange.y;
  420. float sign = MathEx.Sign(pos);
  421. pos = sign*MathEx.Clamp01(MathEx.Abs(pos));
  422. pos = (1.0f - pos) /2.0f;
  423. vertScrollBar.Position = pos;
  424. }
  425. else
  426. vertScrollBar.Position = 0.0f;
  427. }
  428. /// <summary>
  429. /// Calculates the width/height of the curve area depending on the current zoom level.
  430. /// </summary>
  431. /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
  432. private Vector2 GetZoomedRange()
  433. {
  434. float zoomLevel = MathEx.Pow(2, zoomAmount);
  435. Vector2 optimalRange = GetOptimalRange();
  436. return optimalRange / zoomLevel;
  437. }
  438. /// <summary>
  439. /// Returns the total width/height of the contents of the curve area.
  440. /// </summary>
  441. /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
  442. private Vector2 GetTotalRange()
  443. {
  444. // Return optimal range (that covers the visible curve)
  445. Vector2 optimalRange = GetOptimalRange();
  446. // Increase range in case user zoomed out
  447. Vector2 zoomedRange = GetZoomedRange();
  448. return Vector2.Max(optimalRange, zoomedRange);
  449. }
  450. /// <summary>
  451. /// Zooms in or out at the provided position in the curve display.
  452. /// </summary>
  453. /// <param name="curvePos">Position to zoom towards, relative to the curve display area, in curve space
  454. /// (value, time)</param>
  455. /// <param name="amount">Amount to zoom in (positive), or out (negative).</param>
  456. private void Zoom(Vector2 curvePos, float amount)
  457. {
  458. // Increase or decrease the visible range depending on zoom level
  459. Vector2 oldZoomedRange = GetZoomedRange();
  460. zoomAmount = MathEx.Clamp(zoomAmount + amount, -10.0f, 10.0f);
  461. Vector2 zoomedRange = GetZoomedRange();
  462. Vector2 zoomedDiff = zoomedRange - oldZoomedRange;
  463. Vector2 currentRange = guiCurveEditor.Range;
  464. Vector2 newRange = currentRange + zoomedDiff;
  465. guiCurveEditor.Range = newRange;
  466. // When zooming, make sure to focus on the point provided, so adjust the offset
  467. Vector2 rangeScale = newRange;
  468. rangeScale.x /= currentRange.x;
  469. rangeScale.y /= currentRange.y;
  470. Vector2 relativeCurvePos = curvePos - guiCurveEditor.Offset;
  471. Vector2 newCurvePos = relativeCurvePos * rangeScale;
  472. Vector2 diff = newCurvePos - relativeCurvePos;
  473. guiCurveEditor.Offset -= diff;
  474. UpdateScrollBarSize();
  475. UpdateScrollBarPosition();
  476. }
  477. #endregion
  478. #region Curve save/load
  479. private EditorAnimClipInfo clipInfo;
  480. /// <summary>
  481. /// Refreshes the contents of the curve and property display by loading animation curves from the provided
  482. /// animation clip.
  483. /// </summary>
  484. /// <param name="clip">Clip containing the animation to load.</param>
  485. private void LoadAnimClip(AnimationClip clip)
  486. {
  487. EditorPersistentData persistentData = EditorApplication.PersistentData;
  488. if (persistentData.dirtyAnimClips.TryGetValue(clip.UUID, out clipInfo))
  489. {
  490. // If an animation clip is imported, we don't care about it's cached curve values as they could have changed
  491. // since last modification, so we re-load the clip. But we persist the events as those can only be set
  492. // within the editor.
  493. if (clipInfo.isImported)
  494. {
  495. EditorAnimClipInfo newClipInfo = EditorAnimClipInfo.Create(clip);
  496. newClipInfo.events = clipInfo.events;
  497. }
  498. }
  499. else
  500. clipInfo = EditorAnimClipInfo.Create(clip);
  501. persistentData.dirtyAnimClips[clip.UUID] = clipInfo;
  502. foreach (var curve in clipInfo.curves)
  503. guiFieldDisplay.AddField(new AnimFieldInfo(curve.Key, curve.Value, !clipInfo.isImported));
  504. guiCurveEditor.Events = clipInfo.events;
  505. guiCurveEditor.DisableCurveEdit = clipInfo.isImported;
  506. SetCurrentFrame(0);
  507. FPS = clipInfo.sampleRate;
  508. }
  509. /// <summary>
  510. /// Checks if the currently selected object has changed, and rebuilds the GUI and loads the animation clip if needed.
  511. /// </summary>
  512. /// <param name="force">If true the GUI rebuild and animation clip load will be forced regardless if the active
  513. /// scene object changed.</param>
  514. private void UpdateSelectedSO(bool force)
  515. {
  516. SceneObject so = Selection.SceneObject;
  517. if (selectedSO != so || force)
  518. {
  519. if (selectedSO != null && so == null)
  520. {
  521. EditorInput.OnPointerPressed -= OnPointerPressed;
  522. EditorInput.OnPointerMoved -= OnPointerMoved;
  523. EditorInput.OnPointerReleased -= OnPointerReleased;
  524. EditorInput.OnButtonUp -= OnButtonUp;
  525. }
  526. else if (selectedSO == null && so != null)
  527. {
  528. EditorInput.OnPointerPressed += OnPointerPressed;
  529. EditorInput.OnPointerMoved += OnPointerMoved;
  530. EditorInput.OnPointerReleased += OnPointerReleased;
  531. EditorInput.OnButtonUp += OnButtonUp;
  532. }
  533. zoomAmount = 0.0f;
  534. selectedSO = so;
  535. selectedFields.Clear();
  536. clipInfo = null;
  537. RebuildGUI();
  538. // Load existing clip if one exists
  539. if (selectedSO != null)
  540. {
  541. Animation animation = selectedSO.GetComponent<Animation>();
  542. if (animation != null)
  543. {
  544. AnimationClip clip = animation.DefaultClip;
  545. if (clip != null)
  546. LoadAnimClip(clip);
  547. }
  548. }
  549. if(clipInfo == null)
  550. clipInfo = new EditorAnimClipInfo();
  551. if(selectedSO != null)
  552. UpdateDisplayedCurves(true);
  553. }
  554. }
  555. #endregion
  556. #region Record/Playback
  557. /// <summary>
  558. /// Iterates over all curve path fields and records their current state. If the state differs from the current
  559. /// curve values, new keyframes are added.
  560. /// </summary>
  561. /// <param name="time">Time for which to record the state, in seconds.</param>
  562. private void RecordState(float time)
  563. {
  564. Action<EdAnimationCurve, float, float> addOrUpdateKeyframe = (curve, keyTime, keyValue) =>
  565. {
  566. KeyFrame[] keyframes = curve.KeyFrames;
  567. int keyframeIdx = -1;
  568. for (int i = 0; i < keyframes.Length; i++)
  569. {
  570. if (MathEx.ApproxEquals(keyframes[i].time, time))
  571. {
  572. keyframeIdx = i;
  573. break;
  574. }
  575. }
  576. if (keyframeIdx != -1)
  577. curve.UpdateKeyframe(keyframeIdx, keyTime, keyValue);
  578. else
  579. curve.AddKeyframe(keyTime, keyValue);
  580. curve.Apply();
  581. };
  582. foreach (var KVP in clipInfo.curves)
  583. {
  584. string suffix;
  585. SerializableProperty property = Animation.FindProperty(selectedSO, KVP.Key, out suffix);
  586. if (property == null)
  587. continue;
  588. switch (KVP.Value.type)
  589. {
  590. case SerializableProperty.FieldType.Vector2:
  591. {
  592. Vector2 value = property.GetValue<Vector2>();
  593. for (int i = 0; i < 2; i++)
  594. {
  595. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  596. if (!MathEx.ApproxEquals(value[i], curveVal))
  597. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, curveVal);
  598. }
  599. }
  600. break;
  601. case SerializableProperty.FieldType.Vector3:
  602. {
  603. Vector3 value = property.GetValue<Vector3>();
  604. for (int i = 0; i < 3; i++)
  605. {
  606. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  607. if (!MathEx.ApproxEquals(value[i], curveVal))
  608. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, curveVal);
  609. }
  610. }
  611. break;
  612. case SerializableProperty.FieldType.Vector4:
  613. {
  614. if (property.InternalType == typeof(Vector4))
  615. {
  616. Vector4 value = property.GetValue<Vector4>();
  617. for (int i = 0; i < 4; i++)
  618. {
  619. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  620. if (!MathEx.ApproxEquals(value[i], curveVal))
  621. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, curveVal);
  622. }
  623. }
  624. else if (property.InternalType == typeof(Quaternion))
  625. {
  626. Quaternion value = property.GetValue<Quaternion>();
  627. for (int i = 0; i < 4; i++)
  628. {
  629. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  630. if (!MathEx.ApproxEquals(value[i], curveVal))
  631. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, curveVal);
  632. }
  633. }
  634. }
  635. break;
  636. case SerializableProperty.FieldType.Color:
  637. {
  638. Color value = property.GetValue<Color>();
  639. for (int i = 0; i < 4; i++)
  640. {
  641. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  642. if (!MathEx.ApproxEquals(value[i], curveVal))
  643. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, curveVal);
  644. }
  645. }
  646. break;
  647. case SerializableProperty.FieldType.Bool:
  648. {
  649. bool value = property.GetValue<bool>();
  650. bool curveVal = KVP.Value.curveInfos[0].curve.Evaluate(time) > 0.0f;
  651. if (value != curveVal)
  652. addOrUpdateKeyframe(KVP.Value.curveInfos[0].curve, time, curveVal ? 1.0f : -1.0f);
  653. }
  654. break;
  655. case SerializableProperty.FieldType.Int:
  656. {
  657. int value = property.GetValue<int>();
  658. int curveVal = (int)KVP.Value.curveInfos[0].curve.Evaluate(time);
  659. if (value != curveVal)
  660. addOrUpdateKeyframe(KVP.Value.curveInfos[0].curve, time, curveVal);
  661. }
  662. break;
  663. case SerializableProperty.FieldType.Float:
  664. {
  665. float value = property.GetValue<float>();
  666. float curveVal = KVP.Value.curveInfos[0].curve.Evaluate(time);
  667. if (!MathEx.ApproxEquals(value, curveVal))
  668. addOrUpdateKeyframe(KVP.Value.curveInfos[0].curve, time, curveVal);
  669. }
  670. break;
  671. }
  672. }
  673. }
  674. #endregion
  675. #region Curve display
  676. private int currentFrameIdx;
  677. private int fps = 1;
  678. /// <summary>
  679. /// Sampling rate of the animation in frames per second. Determines granularity at which positions keyframes can be
  680. /// placed.
  681. /// </summary>
  682. internal int FPS
  683. {
  684. get { return fps; }
  685. set { guiCurveEditor.SetFPS(value); fps = MathEx.Max(value, 1); }
  686. }
  687. /// <summary>
  688. /// Changes the currently selected frame in the curve display.
  689. /// </summary>
  690. /// <param name="frameIdx">Index of the frame to select.</param>
  691. private void SetCurrentFrame(int frameIdx)
  692. {
  693. currentFrameIdx = Math.Max(0, frameIdx);
  694. frameInputField.Value = currentFrameIdx;
  695. guiCurveEditor.SetMarkedFrame(currentFrameIdx);
  696. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  697. List<GUIAnimFieldPathValue> values = new List<GUIAnimFieldPathValue>();
  698. foreach (var kvp in clipInfo.curves)
  699. {
  700. GUIAnimFieldPathValue fieldValue = new GUIAnimFieldPathValue();
  701. fieldValue.path = kvp.Key;
  702. switch (kvp.Value.type)
  703. {
  704. case SerializableProperty.FieldType.Vector2:
  705. {
  706. Vector2 value = new Vector2();
  707. for (int i = 0; i < 2; i++)
  708. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  709. fieldValue.value = value;
  710. }
  711. break;
  712. case SerializableProperty.FieldType.Vector3:
  713. {
  714. Vector3 value = new Vector3();
  715. for (int i = 0; i < 3; i++)
  716. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  717. fieldValue.value = value;
  718. }
  719. break;
  720. case SerializableProperty.FieldType.Vector4:
  721. {
  722. Vector4 value = new Vector4();
  723. for (int i = 0; i < 4; i++)
  724. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  725. fieldValue.value = value;
  726. }
  727. break;
  728. case SerializableProperty.FieldType.Color:
  729. {
  730. Color value = new Color();
  731. for (int i = 0; i < 4; i++)
  732. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  733. fieldValue.value = value;
  734. }
  735. break;
  736. case SerializableProperty.FieldType.Bool:
  737. case SerializableProperty.FieldType.Int:
  738. case SerializableProperty.FieldType.Float:
  739. fieldValue.value = kvp.Value.curveInfos[0].curve.Evaluate(time, false); ;
  740. break;
  741. }
  742. values.Add(fieldValue);
  743. }
  744. guiFieldDisplay.SetDisplayValues(values.ToArray());
  745. }
  746. /// <summary>
  747. /// Returns a list of all animation curves that should be displayed in the curve display.
  748. /// </summary>
  749. /// <returns>Array of curves to display.</returns>
  750. private CurveDrawInfo[] GetDisplayedCurves()
  751. {
  752. List<CurveDrawInfo> curvesToDisplay = new List<CurveDrawInfo>();
  753. if (selectedFields.Count == 0) // Display all if nothing is selected
  754. {
  755. if (clipInfo == null)
  756. return curvesToDisplay.ToArray();
  757. foreach (var curve in clipInfo.curves)
  758. {
  759. for (int i = 0; i < curve.Value.curveInfos.Length; i++)
  760. curvesToDisplay.Add(curve.Value.curveInfos[i]);
  761. }
  762. }
  763. else
  764. {
  765. for (int i = 0; i < selectedFields.Count; i++)
  766. {
  767. CurveDrawInfo[] curveInfos;
  768. if (TryGetCurve(selectedFields[i], out curveInfos))
  769. curvesToDisplay.AddRange(curveInfos);
  770. }
  771. }
  772. return curvesToDisplay.ToArray();
  773. }
  774. /// <summary>
  775. /// Returns width/height required to show the entire contents of the currently displayed curves.
  776. /// </summary>
  777. /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
  778. private Vector2 GetOptimalRange()
  779. {
  780. CurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
  781. float xRange;
  782. float yRange;
  783. CalculateRange(curvesToDisplay, out xRange, out yRange);
  784. // Add padding to y range
  785. yRange *= 1.05f;
  786. // Don't allow zero range
  787. if (xRange == 0.0f)
  788. xRange = 60.0f;
  789. if (yRange == 0.0f)
  790. yRange = 10.0f;
  791. return new Vector2(xRange, yRange);
  792. }
  793. /// <summary>
  794. /// Calculates an unique color for each animation curve.
  795. /// </summary>
  796. private void UpdateCurveColors()
  797. {
  798. int globalCurveIdx = 0;
  799. foreach (var curveGroup in clipInfo.curves)
  800. {
  801. for (int i = 0; i < curveGroup.Value.curveInfos.Length; i++)
  802. curveGroup.Value.curveInfos[i].color = GUICurveDrawing.GetUniqueColor(globalCurveIdx++);
  803. }
  804. }
  805. /// <summary>
  806. /// Updates the curve display with currently selected curves.
  807. /// </summary>
  808. /// <param name="allowReduce">Normally the curve display will expand if newly selected curves cover a larger area
  809. /// than currently available, but the area won't be reduced if the selected curves cover
  810. /// a smaller area. Set this to true to allow the area to be reduced.</param>
  811. private void UpdateDisplayedCurves(bool allowReduce = false)
  812. {
  813. CurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
  814. guiCurveEditor.SetCurves(curvesToDisplay);
  815. Vector2 newRange = GetOptimalRange();
  816. if (!allowReduce)
  817. {
  818. // Don't reduce visible range
  819. newRange.x = Math.Max(newRange.x, guiCurveEditor.Range.x);
  820. newRange.y = Math.Max(newRange.y, guiCurveEditor.Range.y);
  821. }
  822. guiCurveEditor.Range = newRange;
  823. UpdateScrollBarSize();
  824. }
  825. #endregion
  826. #region Field display
  827. private List<string> selectedFields = new List<string>();
  828. /// <summary>
  829. /// Registers a new animation curve field.
  830. /// </summary>
  831. /// <param name="path">Path of the field, see <see cref="GUIFieldSelector.OnElementSelected"/></param>
  832. /// <param name="type">Type of the field (float, vector, etc.)</param>
  833. private void AddNewField(string path, SerializableProperty.FieldType type)
  834. {
  835. bool noSelection = selectedFields.Count == 0;
  836. switch (type)
  837. {
  838. case SerializableProperty.FieldType.Vector4:
  839. {
  840. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  841. fieldCurves.type = type;
  842. fieldCurves.curveInfos = new CurveDrawInfo[4];
  843. string[] subPaths = { ".x", ".y", ".z", ".w" };
  844. for (int i = 0; i < subPaths.Length; i++)
  845. {
  846. string subFieldPath = path + subPaths[i];
  847. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  848. selectedFields.Add(subFieldPath);
  849. }
  850. clipInfo.curves[path] = fieldCurves;
  851. }
  852. break;
  853. case SerializableProperty.FieldType.Vector3:
  854. {
  855. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  856. fieldCurves.type = type;
  857. fieldCurves.curveInfos = new CurveDrawInfo[3];
  858. string[] subPaths = { ".x", ".y", ".z" };
  859. for (int i = 0; i < subPaths.Length; i++)
  860. {
  861. string subFieldPath = path + subPaths[i];
  862. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  863. selectedFields.Add(subFieldPath);
  864. }
  865. clipInfo.curves[path] = fieldCurves;
  866. }
  867. break;
  868. case SerializableProperty.FieldType.Vector2:
  869. {
  870. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  871. fieldCurves.type = type;
  872. fieldCurves.curveInfos = new CurveDrawInfo[2];
  873. string[] subPaths = { ".x", ".y" };
  874. for (int i = 0; i < subPaths.Length; i++)
  875. {
  876. string subFieldPath = path + subPaths[i];
  877. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  878. selectedFields.Add(subFieldPath);
  879. }
  880. clipInfo.curves[path] = fieldCurves;
  881. }
  882. break;
  883. case SerializableProperty.FieldType.Color:
  884. {
  885. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  886. fieldCurves.type = type;
  887. fieldCurves.curveInfos = new CurveDrawInfo[4];
  888. string[] subPaths = { ".r", ".g", ".b", ".a" };
  889. for (int i = 0; i < subPaths.Length; i++)
  890. {
  891. string subFieldPath = path + subPaths[i];
  892. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  893. selectedFields.Add(subFieldPath);
  894. }
  895. clipInfo.curves[path] = fieldCurves;
  896. }
  897. break;
  898. default: // Primitive type
  899. {
  900. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  901. fieldCurves.type = type;
  902. fieldCurves.curveInfos = new CurveDrawInfo[1];
  903. fieldCurves.curveInfos[0].curve = new EdAnimationCurve();
  904. selectedFields.Add(path);
  905. clipInfo.curves[path] = fieldCurves;
  906. }
  907. break;
  908. }
  909. UpdateCurveColors();
  910. UpdateDisplayedFields();
  911. EditorApplication.SetProjectDirty();
  912. UpdateDisplayedCurves(noSelection);
  913. }
  914. /// <summary>
  915. /// Selects a new animation curve field, making the curve display in the curve display GUI element.
  916. /// </summary>
  917. /// <param name="path">Path of the field to display.</param>
  918. /// <param name="additive">If true the field will be shown along with any already selected fields, or if false
  919. /// only the provided field will be shown.</param>
  920. private void SelectField(string path, bool additive)
  921. {
  922. if (!additive)
  923. selectedFields.Clear();
  924. bool noSelection = selectedFields.Count == 0;
  925. if (!string.IsNullOrEmpty(path))
  926. {
  927. selectedFields.RemoveAll(x => { return x == path || IsPathParent(x, path); });
  928. selectedFields.Add(path);
  929. }
  930. guiFieldDisplay.SetSelection(selectedFields.ToArray());
  931. UpdateDisplayedCurves(noSelection);
  932. }
  933. /// <summary>
  934. /// Deletes all currently selecting fields, removing them their curves permanently.
  935. /// </summary>
  936. private void RemoveSelectedFields()
  937. {
  938. for (int i = 0; i < selectedFields.Count; i++)
  939. clipInfo.curves.Remove(GetSubPathParent(selectedFields[i]));
  940. UpdateCurveColors();
  941. UpdateDisplayedFields();
  942. selectedFields.Clear();
  943. EditorApplication.SetProjectDirty();
  944. UpdateDisplayedCurves();
  945. }
  946. /// <summary>
  947. /// Updates the GUI element displaying the current animation curve fields.
  948. /// </summary>
  949. private void UpdateDisplayedFields()
  950. {
  951. List<AnimFieldInfo> existingFields = new List<AnimFieldInfo>();
  952. foreach (var KVP in clipInfo.curves)
  953. existingFields.Add(new AnimFieldInfo(KVP.Key, KVP.Value, !clipInfo.isImported));
  954. guiFieldDisplay.SetFields(existingFields.ToArray());
  955. }
  956. #endregion
  957. #region Helpers
  958. /// <summary>
  959. /// Returns the size of the curve editor GUI element.
  960. /// </summary>
  961. /// <returns>Width/height of the curve editor, in pixels.</returns>
  962. private Vector2I GetCurveEditorSize()
  963. {
  964. Vector2I output = new Vector2I();
  965. output.x = Math.Max(0, Width - FIELD_DISPLAY_WIDTH - scrollBarWidth);
  966. output.y = Math.Max(0, Height - buttonLayoutHeight - scrollBarHeight);
  967. return output;
  968. }
  969. /// <summary>
  970. /// Calculates the total range covered by a set of curves.
  971. /// </summary>
  972. /// <param name="curveInfos">Curves to calculate range for.</param>
  973. /// <param name="xRange">Maximum time value present in the curves.</param>
  974. /// <param name="yRange">Maximum absolute curve value present in the curves.</param>
  975. private static void CalculateRange(CurveDrawInfo[] curveInfos, out float xRange, out float yRange)
  976. {
  977. // Note: This only evaluates at keyframes, we should also evaluate in-between in order to account for steep
  978. // tangents
  979. xRange = 0.0f;
  980. yRange = 0.0f;
  981. foreach (var curveInfo in curveInfos)
  982. {
  983. KeyFrame[] keyframes = curveInfo.curve.KeyFrames;
  984. foreach (var key in keyframes)
  985. {
  986. xRange = Math.Max(xRange, key.time);
  987. yRange = Math.Max(yRange, Math.Abs(key.value));
  988. }
  989. }
  990. }
  991. /// <summary>
  992. /// Attempts to find a curve field at the specified path.
  993. /// </summary>
  994. /// <param name="path">Path of the curve field to look for.</param>
  995. /// <param name="curveInfos">One or multiple curves found for the specific path (one field can have multiple curves
  996. /// if it is a complex type, like a vector).</param>
  997. /// <returns>True if the curve field was found, false otherwise.</returns>
  998. private bool TryGetCurve(string path, out CurveDrawInfo[] curveInfos)
  999. {
  1000. int index = path.LastIndexOf(".");
  1001. string parentPath;
  1002. string subPathSuffix = null;
  1003. if (index == -1)
  1004. {
  1005. parentPath = path;
  1006. }
  1007. else
  1008. {
  1009. parentPath = path.Substring(0, index);
  1010. subPathSuffix = path.Substring(index, path.Length - index);
  1011. }
  1012. FieldAnimCurves fieldCurves;
  1013. if (clipInfo.curves.TryGetValue(parentPath, out fieldCurves))
  1014. {
  1015. if (!string.IsNullOrEmpty(subPathSuffix))
  1016. {
  1017. if (subPathSuffix == ".x" || subPathSuffix == ".r")
  1018. {
  1019. curveInfos = new [] { fieldCurves.curveInfos[0] };
  1020. return true;
  1021. }
  1022. else if (subPathSuffix == ".y" || subPathSuffix == ".g")
  1023. {
  1024. curveInfos = new[] { fieldCurves.curveInfos[1] };
  1025. return true;
  1026. }
  1027. else if (subPathSuffix == ".z" || subPathSuffix == ".b")
  1028. {
  1029. curveInfos = new[] { fieldCurves.curveInfos[2] };
  1030. return true;
  1031. }
  1032. else if (subPathSuffix == ".w" || subPathSuffix == ".a")
  1033. {
  1034. curveInfos = new[] { fieldCurves.curveInfos[3] };
  1035. return true;
  1036. }
  1037. }
  1038. else
  1039. {
  1040. curveInfos = fieldCurves.curveInfos;
  1041. return true;
  1042. }
  1043. }
  1044. curveInfos = new CurveDrawInfo[0];
  1045. return false;
  1046. }
  1047. /// <summary>
  1048. /// Checks if one curve field path a parent of the other.
  1049. /// </summary>
  1050. /// <param name="child">Path to check if it is a child of <paramref name="parent"/>.</param>
  1051. /// <param name="parent">Path to check if it is a parent of <paramref name="child"/>.</param>
  1052. /// <returns>True if <paramref name="child"/> is a child of <paramref name="parent"/>.</returns>
  1053. private bool IsPathParent(string child, string parent)
  1054. {
  1055. string[] childEntries = child.Split('/', '.');
  1056. string[] parentEntries = parent.Split('/', '.');
  1057. if (parentEntries.Length >= child.Length)
  1058. return false;
  1059. int compareLength = Math.Min(childEntries.Length, parentEntries.Length);
  1060. for (int i = 0; i < compareLength; i++)
  1061. {
  1062. if (childEntries[i] != parentEntries[i])
  1063. return false;
  1064. }
  1065. return true;
  1066. }
  1067. /// <summary>
  1068. /// If a path has sub-elements (e.g. .x, .r), returns a path without those elements. Otherwise returns the original
  1069. /// path.
  1070. /// </summary>
  1071. /// <param name="path">Path to check.</param>
  1072. /// <returns>Path without sub-elements.</returns>
  1073. private string GetSubPathParent(string path)
  1074. {
  1075. int index = path.LastIndexOf(".");
  1076. if (index == -1)
  1077. return path;
  1078. return path.Substring(0, index);
  1079. }
  1080. #endregion
  1081. #region Input callbacks
  1082. /// <summary>
  1083. /// Triggered when the user presses a mouse button.
  1084. /// </summary>
  1085. /// <param name="ev">Information about the mouse press event.</param>
  1086. private void OnPointerPressed(PointerEvent ev)
  1087. {
  1088. guiCurveEditor.OnPointerPressed(ev);
  1089. if (ev.button == PointerButton.Middle)
  1090. {
  1091. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  1092. Vector2 curvePos;
  1093. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  1094. {
  1095. dragStartPos = windowPos;
  1096. isButtonHeld = true;
  1097. }
  1098. }
  1099. }
  1100. /// <summary>
  1101. /// Triggered when the user moves the mouse.
  1102. /// </summary>
  1103. /// <param name="ev">Information about the mouse move event.</param>
  1104. private void OnPointerMoved(PointerEvent ev)
  1105. {
  1106. guiCurveEditor.OnPointerMoved(ev);
  1107. if (isButtonHeld)
  1108. {
  1109. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  1110. int distance = Vector2I.Distance(dragStartPos, windowPos);
  1111. if (distance >= DRAG_START_DISTANCE)
  1112. {
  1113. isDragInProgress = true;
  1114. Cursor.Hide();
  1115. Rect2I clipRect;
  1116. clipRect.x = ev.ScreenPos.x - 2;
  1117. clipRect.y = ev.ScreenPos.y - 2;
  1118. clipRect.width = 4;
  1119. clipRect.height = 4;
  1120. Cursor.ClipToRect(clipRect);
  1121. }
  1122. }
  1123. }
  1124. /// <summary>
  1125. /// Triggered when the user releases a mouse button.
  1126. /// </summary>
  1127. /// <param name="ev">Information about the mouse release event.</param>
  1128. private void OnPointerReleased(PointerEvent ev)
  1129. {
  1130. if (isDragInProgress)
  1131. {
  1132. Cursor.Show();
  1133. Cursor.ClipDisable();
  1134. }
  1135. isButtonHeld = false;
  1136. isDragInProgress = false;
  1137. guiCurveEditor.OnPointerReleased(ev);
  1138. }
  1139. /// <summary>
  1140. /// Triggered when the user releases a keyboard button.
  1141. /// </summary>
  1142. /// <param name="ev">Information about the keyboard release event.</param>
  1143. private void OnButtonUp(ButtonEvent ev)
  1144. {
  1145. guiCurveEditor.OnButtonUp(ev);
  1146. }
  1147. #endregion
  1148. #region General callbacks
  1149. /// <summary>
  1150. /// Triggered by the field selector, when user selects a new curve field.
  1151. /// </summary>
  1152. /// <param name="path">Path of the selected curve field.</param>
  1153. /// <param name="type">Type of the selected curve field (float, vector, etc.).</param>
  1154. private void OnFieldAdded(string path, SerializableProperty.FieldType type)
  1155. {
  1156. // Remove the root scene object from the path (we know which SO it is, no need to hardcode its name in the path)
  1157. string pathNoRoot = path.TrimStart('/');
  1158. int separatorIdx = pathNoRoot.IndexOf("/");
  1159. if (separatorIdx == -1 || (separatorIdx + 1) >= pathNoRoot.Length)
  1160. return;
  1161. pathNoRoot = pathNoRoot.Substring(separatorIdx + 1, pathNoRoot.Length - separatorIdx - 1);
  1162. AddNewField(pathNoRoot, type);
  1163. }
  1164. /// <summary>
  1165. /// Triggered when the user moves or resizes the horizontal scrollbar.
  1166. /// </summary>
  1167. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1168. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1169. private void OnHorzScrollOrResize(float position, float size)
  1170. {
  1171. SetHorzScrollbarProperties(position, size);
  1172. }
  1173. /// <summary>
  1174. /// Triggered when the user moves or resizes the vertical scrollbar.
  1175. /// </summary>
  1176. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1177. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1178. private void OnVertScrollOrResize(float position, float size)
  1179. {
  1180. SetVertScrollbarProperties(position, size);
  1181. }
  1182. /// <summary>
  1183. /// Triggered when the user selects a new curve field.
  1184. /// </summary>
  1185. /// <param name="path">Path of the selected curve field.</param>
  1186. private void OnFieldSelected(string path)
  1187. {
  1188. bool additive = Input.IsButtonHeld(ButtonCode.LeftShift) || Input.IsButtonHeld(ButtonCode.RightShift);
  1189. SelectField(path, additive);
  1190. }
  1191. /// <summary>
  1192. /// Triggered when the user selects a new scene object or a resource.
  1193. /// </summary>
  1194. /// <param name="sceneObjects">Newly selected scene objects.</param>
  1195. /// <param name="resourcePaths">Newly selected resources.</param>
  1196. private void OnSelectionChanged(SceneObject[] sceneObjects, string[] resourcePaths)
  1197. {
  1198. UpdateSelectedSO(false);
  1199. }
  1200. /// <summary>
  1201. /// Triggered when the user selects a new frame in the curve display.
  1202. /// </summary>
  1203. /// <param name="frameIdx">Index of the selected frame.</param>
  1204. private void OnFrameSelected(int frameIdx)
  1205. {
  1206. SetCurrentFrame(frameIdx);
  1207. }
  1208. /// <summary>
  1209. /// Triggered when the user changed (add, removed or modified) animation events in the curve display.
  1210. /// </summary>
  1211. private void OnEventsChanged()
  1212. {
  1213. clipInfo.events = guiCurveEditor.Events;
  1214. EditorApplication.SetProjectDirty();
  1215. }
  1216. #endregion
  1217. }
  1218. /// <summary>
  1219. /// Drop down window that displays options used by the animation window.
  1220. /// </summary>
  1221. [DefaultSize(100, 50)]
  1222. internal class AnimationOptions : DropDownWindow
  1223. {
  1224. /// <summary>
  1225. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1226. /// use.
  1227. /// </summary>
  1228. /// <param name="parent">Animation window that this drop down window is a part of.</param>
  1229. internal void Initialize(AnimationWindow parent)
  1230. {
  1231. GUIIntField fpsField = new GUIIntField(new LocEdString("FPS"), 40);
  1232. fpsField.Value = parent.FPS;
  1233. fpsField.OnChanged += x => { parent.FPS = x; };
  1234. GUILayoutY vertLayout = GUI.AddLayoutY();
  1235. vertLayout.AddFlexibleSpace();
  1236. GUILayoutX contentLayout = vertLayout.AddLayoutX();
  1237. contentLayout.AddFlexibleSpace();
  1238. contentLayout.AddElement(fpsField);
  1239. contentLayout.AddFlexibleSpace();
  1240. vertLayout.AddFlexibleSpace();
  1241. }
  1242. }
  1243. /** @} */
  1244. }