AnimationWindow.cs 65 KB

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